using Dapper;
using LAPS_WATCHER.Models;
using LAPS_WATCHER.Models.Configuration;
using Microsoft.AspNetCore.Http.Features;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LAPS_WATCHER.App_Data
{
    public class CommonRepository
    {
       // useractivitylogModel userlogmodel;

        public IEnumerable<servermasterModel> getServerInfo()
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spservermasterselect";
                param.Add("servermasterid_p", dbType: DbType.Int32, value: null, direction: ParameterDirection.Input);
                return dbConnection.Query<servermasterModel>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        //get the list of available action list
        public IEnumerable<object> getActionList()
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spgetactionlist";
                return dbConnection.Query<object>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        public string connectlinux()
        {
            string fileName = @"/efs/connectlinux.txt";

            try
            {
                // Check if file already exists. If yes, delete it.     
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                bool isWindows = System.Runtime.InteropServices.RuntimeInformation
                                               .IsOSPlatform(OSPlatform.Windows);
                // Create a new file     
                using (FileStream fs = File.Create(fileName))
                {
                    // Add some text to file    
                    Byte[] title = new UTF8Encoding(true).GetBytes("Log file");
                    fs.Write(title, 0, title.Length);
                   
                }

                // Open the stream and read it back.    
                using (StreamReader sr = File.OpenText(fileName))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(s);
                    }
                }
            }
            catch (Exception Ex)
            {
                ErrorLog(Ex);
                Console.WriteLine(Ex.ToString());
            }
            return fileName;
        }

         private StringBuilder getmailcontentformated(string mailcontent, string typedetails)
        {
            StringBuilder sbody = new StringBuilder();

            MatchCollection myMatchCollection = Regex.Matches(mailcontent, @"\$\w+(?:.(\w+))?");
            foreach (Match myMatch in myMatchCollection)
            {
                //Console.WriteLine(myMatch);
                var fieldname = Regex.Replace(myMatch.Value.ToString(), @"\$|\s+(?=\w+$)", "");
                JArray jsonArray = JArray.Parse(typedetails);
                JObject array = JObject.Parse(jsonArray[0].ToString());

                foreach (KeyValuePair<String, JToken> app in array)
                {

                    var appName = app.Key;
                    if (fieldname.ToLower() == appName.ToLower())
                    {
                        var appValue = (String)app.Value;
                        if ((appValue != string.Empty) && (appValue != null) && (appValue != null))
                        {
                            //if (appName.Contains("size"))
                            //{
                            //    appValue = FileSizeFormatter.FormatSize(Convert.ToInt32(appValue));
                            //}

                            var regex = new Regex(Regex.Escape("$" + myMatch.Value.ToString()));
                            mailcontent = regex.Replace(mailcontent, appValue, 1);

                        }
                        else
                        {
                            var regex = new Regex(Regex.Escape("$" + myMatch.Value.ToString()));
                            mailcontent = regex.Replace(mailcontent, "-", 1);
                            // mailcontent = mailcontent.Replace("$" + myMatch.Value.ToString(), "");
                        }

                    }
                }
                if (myMatch.Value.ToString().Contains(fieldname.ToLower()) && myMatch.Value.ToString() != "$documentlink" && myMatch.Value.ToString() != "$downloadlink")
                {
                    mailcontent = mailcontent.Replace("$" + myMatch.Value.ToString(), "");
                }

            }
            sbody.Append(mailcontent);
            return sbody;


        }

        public DataTable JsonStringToDataTable(string jsonString)
        {
            DataTable dt = new DataTable();
            string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
            List<string> ColumnsName = new List<string>();
            foreach (string jSA in jsonStringArray)
            {
                string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
                foreach (string ColumnsNameData in jsonStringData)
                {
                    try
                    {
                        int idx = ColumnsNameData.IndexOf(":");
                        string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
                        if (!ColumnsName.Contains(ColumnsNameString))
                        {
                            ColumnsName.Add(ColumnsNameString);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message.ToString());
                        throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData));
                    }
                }
                break;
            }
            foreach (string AddColumnName in ColumnsName)
            {
                dt.Columns.Add(AddColumnName);
            }
            foreach (string jSA in jsonStringArray)
            {
                string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
                DataRow nr = dt.NewRow();
                foreach (string rowData in RowData)
                {
                    try
                    {
                        int idx = rowData.IndexOf(":");
                        string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
                        string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
                        nr[RowColumns] = RowDataString;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message.ToString());
                        continue;
                    }
                }
                dt.Rows.Add(nr);
            }
            return dt;
        }

        public int emailhistorysave(sentemailhistoryModel data)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                int result = 0;
                string input = JsonConvert.SerializeObject(data);
                const string query = @"public.spmailsenthistory";
                var param = new DynamicParameters();
                param.Add("inputjsonstr", dbType: DbType.String, value: input, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: "insert", direction: ParameterDirection.Input);
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();
                return result;
            }
        }

        public int emailhistorystatusupdate(sentemailhistoryModel data)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                int result = 0;
                string input = JsonConvert.SerializeObject(data);
                const string query = @"public.spmailsenthistory";
                var param = new DynamicParameters();
                param.Add("inputjsonstr", dbType: DbType.String, value: input, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: "update", direction: ParameterDirection.Input);
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();
                return result;
            }
        }

        //public string getemailidfromjson(JArray mailidjson)
        //{
        //    string emailids = "";
        //    UserRepository oUserRepository = new UserRepository();
        //    userModel user;

        //    foreach (JToken maildetails in mailidjson)
        //    {
        //        if (maildetails["userid"] != null && (string)maildetails["userid"] != "")
        //        {
        //            user = new userModel();
        //            user =(userModel) oUserRepository.FindByID((int)maildetails["userid"]);
        //            if (user.emailid != "" && user.emailid != null)
        //            {
        //                if (emailids == "")
        //                    emailids = user.emailid;
        //                else
        //                    emailids = emailids + "," + user.emailid;
        //            }
        //        }
        //    }
        //    return emailids;
        //}

        public void ErrorLog(Exception ex)
        {
            try
            {
                //string filePath = @"C:\Error.txt";
                //string a = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
                //DriveInfo cDrive = new DriveInfo(System.Environment.CurrentDirectory);
                //string b = cDrive.RootDirectory.ToString();
                //string c = AppDomain.CurrentDomain.BaseDirectory;
                string d = System.IO.Directory.GetCurrentDirectory();
                //  File.WriteAllText(d, sb.ToString());
                using (StreamWriter writer = new StreamWriter(d + "\\error.log.txt", true))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("------------------------Error Log start----------------------------");
                    sb.AppendLine("Date:-" + DateTime.Now.ToString());
                    sb.AppendLine("Application Name :" + ex.Source);
                    sb.AppendLine("Error Message :" + ex.Message);
                    sb.AppendLine("Method Name :" + ex.StackTrace);
                    sb.AppendLine("------------------------Error Log End----------------------------");
                    writer.WriteLine(sb.ToString());
                    writer.Close();
                    // tw.WriteLine("The next line!");
                };
            }
            catch (Exception)
            {

            }
            //System.IO.File.WriteAllText(d+"\\error.log.txt", sb.ToString());
        }

        public string removeUnwantedFieldName(string mailContent)
        {
            string returnvalue = string.Empty;
            MatchCollection myMatchCollection = Regex.Matches(mailContent, @"\$\$[^ ]+(?= |$)");
            if (myMatchCollection.Count != 0)
            {
                foreach (Match myMatch in myMatchCollection)
                {
                    mailContent = mailContent.Replace(myMatch.Value.ToString(), " ");
                    returnvalue = mailContent;
                }
            }
            else
                returnvalue = mailContent;
            return returnvalue;
        }

        public static string CombinedStringBuilder(List<int> list)
        {
            try
            {
                StringBuilder combindedString = new StringBuilder();
                foreach (var item in list)
                {
                    var strappend = item;
                    combindedString.Append(strappend).Append(",");
                }
                if (!string.IsNullOrEmpty(combindedString.ToString()))
                {
                    combindedString.Length = combindedString.Length - 1;
                }
                return combindedString.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string GetServerDateRep(string mode)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    var param = new DynamicParameters();
                    const string query = @"public.spselectserverdatetime";
                    param.Add("mode_p", dbType: DbType.String, value: mode.ToLower(), direction: ParameterDirection.Input);
                    return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                ErrorLog(ex);
                return ex.Message;
            }
        }

        public static void useractivityAdd(useractivitylogModel userlog)
        {

            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                var claimsIdentity = LAPS_WATCHER.App_Data.AppContext.Current.User.Identity as ClaimsIdentity;
                var userId = claimsIdentity.FindFirst(ClaimTypes.Name)?.Value;
                //var accessToken = LotusNotesService.App_Data.AppContext.Current.Request.Headers["Authorization"];

                userlog.userid = Convert.ToInt32(userId);
                userlog.ipaddress = LAPS_WATCHER.App_Data.AppContext.Current.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress?.ToString();
                string output = JsonConvert.SerializeObject(userlog);
                DynamicParameters param = new DynamicParameters();
                param.Add("inputjsonstr", output);
                param.Add("mode_p", "insert");
                dbConnection.Open();
                dbConnection.Execute("spuseractivitylog", param, commandType: CommandType.StoredProcedure);
            }

        }

        public string subjectFieldsReplacement(mailconfigModel maildetails, string fielddetails, string type)
        {
            string result = "";
            MatchCollection myMatchCollection = Regex.Matches(maildetails.subject, @"\$\$[^ ]+(?= |$)");
            JArray jsonArray = JArray.Parse(fielddetails);
            JObject fieldData = JObject.Parse(jsonArray[0].ToString());
            if (myMatchCollection.Count != 0)
            {
                result = maildetails.subject;
                foreach (Match myMatch in myMatchCollection)
                {
                    var splitDollar = myMatch.ToString().Split("$$");
                    string replaceData = string.Empty;
                    if (splitDollar.Count() != 0)
                    {
                        JProperty prop = fieldData.Properties().FirstOrDefault(p => p.Name.ToLower().Contains(splitDollar[1].ToString().ToLower()));
                        replaceData = prop != null ? prop.Value.ToString() : "";
                        result = result.Replace(myMatch.ToString(), replaceData);
                    }
                }
            }
            return result;
        }

        public StringBuilder formatMailContent(string mailcontent, object details)
        {
            StringBuilder sbody = new StringBuilder();
            MatchCollection myMatchCollection = Regex.Matches(mailcontent, @"\$\w+(?:.(\w+))?");

            foreach (Match myMatch in myMatchCollection)
            {
                var fieldname = Regex.Replace(myMatch.Value.ToString(), @"\$|\s+(?=\w+$)", "");
                Type myType = details.GetType();
                IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
                foreach (PropertyInfo prop in props)
                {
                    if (prop.Name.ToLower() == fieldname.ToString().ToLower())
                    {
                        var propValue = (String)prop.GetValue(details, null);
                        if ((propValue != null) && (propValue.ToString() != string.Empty))
                        {
                            var regex = new Regex(Regex.Escape("$" + myMatch.Value.ToString()));
                            mailcontent = regex.Replace(mailcontent, propValue.ToString(), 1);
                        }
                        else
                        {
                            var regex = new Regex(Regex.Escape("$" + myMatch.Value.ToString()));
                            mailcontent = regex.Replace(mailcontent, "-", 1);
                        }
                    }
                }
                if (myMatch.Value.ToString().Contains(fieldname.ToLower()))
                {
                    mailcontent = mailcontent.Replace("$" + myMatch.Value.ToString(), "");
                }

            }
            sbody.Append(mailcontent);
            return sbody;


        }

        //get the list of available action list
        public IEnumerable<object> getRoleMappedMenu(int userid)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.sprolemappedmenu";
                param.Add("userid_p", dbType: DbType.Int32, value: userid, direction: ParameterDirection.Input);
                param.Add("parent_p", dbType: DbType.Int32, value: 0, direction: ParameterDirection.Input);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        //Common function to Execute Stored procedure to select records
        public static object ExecuteSP_ReturnList(string spname, string inputjsonstring, string mode)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", inputjsonstring);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        //Common function to Execute Stored procedure for insert update and delete 
        public static int ExecuteSP_ReturnInt(string spname, object data, string mode, string loglabel)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                string input = JsonConvert.SerializeObject(data);
                int result = 0;

                string query = spname;
                var param = new DynamicParameters();
                param.Add("inputjsonstr", dbType: DbType.String, value: input, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();

                ////code to add user activity log
                //if (result != 0)
                //{


                //    useractivitylogModel userlogmodel = new useractivitylogModel();
                //    userlogmodel.useraction = loglabel + result;
                //    userlogmodel.description = loglabel + result;
                //    useractivityAdd(userlogmodel);
                //}
                return result;
            }
        }


        //Check the given name is exists or not
        public bool CheckExists(string spname, string mode, object inputjsonval)
        {
            bool result = false;
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                string input = JsonConvert.SerializeObject(inputjsonval);
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", input);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                var _list = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).ToList();

                if (_list.Count() > 0 && _list.ToList()[0] != null)
                    result = true;
                return result;
            }
        }

        public bool CheckExistsWithMessage(string spname, string mode, object inputjsonval, ref string message)
        {
            bool result = false;
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {

                dbConnection.Open();
                string input = JsonConvert.SerializeObject(inputjsonval);
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", input);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                var _list = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).ToList();

                if (_list.Count() > 0 && _list.ToList()[0] != null)
                {
                    message = _list[0];

                    JObject obj = JObject.Parse(_list[0]);
                    string msg = (string)obj["message"];
                    if (msg.ToString().Trim().Length > 0)
                        result = true;
                }
                return result;
            }
        }
        //Common function to Execute Stored procedure to select records
        public static lotmasterModel ExecuteSP_ReturnListForLot(string spname, string inputjsonstring, string mode)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                var ds = JsonConvert.DeserializeObject<lotmasterModel>(inputjsonstring);
                param.Add("p_tranid", dbType: DbType.Int32, value: ds.transactionid, direction: ParameterDirection.Input);
                param.Add("p_lotid", dbType: DbType.Int32, value: ds.lotid, direction: ParameterDirection.Input);
                param.Add("p_option", dbType: DbType.String, value: ds.option, direction: ParameterDirection.Input);
                return dbConnection.Query<lotmasterModel>(query, param, commandType: CommandType.StoredProcedure).FirstOrDefault();
            }
        }

        //Common function to Execute Stored procedure to select records with out mode
        public object ExecuteSP_ReturnListwithoutmode(string spname, string inputjsonstring)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", inputjsonstring);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        public static object ExecuteSP_ReturnList1(string spname, string inputjsonstring)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", inputjsonstring);

                var list = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).ToList();
                return list[0];
            }
        }
        //Common function to Execute Stored procedure to select records
        public static object ExecuteSP_ReturnList2(string spname, string inputjsonstring, string mode)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", inputjsonstring);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                var list = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).ToList();
                return list[0];
            }
        }
        public static servermasterModel getfilesavelocation(string spname, string inputjsonstring)
        {
            servermasterModel dt = new servermasterModel();
            try
            {
                bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                if (isWindows)
                {
                    IEnumerable<servermasterModel> sm = getServerInfoByos(spname, inputjsonstring, "Windows").ToList();
                    // string root_path = sm.First().serverpath.ToString();
                    // return root_path;
                    servermasterModel root_path = sm.First();
                    return root_path;
                }
                else
                {
                    IEnumerable<servermasterModel> sm = getServerInfoByos(spname, inputjsonstring, "Linux").ToList();
                    servermasterModel root_path = sm.First();
                    return root_path;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            return dt;
        }

        public static IEnumerable<servermasterModel> getServerInfoByos(string spname, string inputjsonstring, string ostype)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                var ds = JsonConvert.DeserializeObject<lotmasterModel>(inputjsonstring);
                param.Add("p_tranid", dbType: DbType.Int32, value: ds.transactionid, direction: ParameterDirection.Input);
                param.Add("p_lotid", dbType: DbType.Int32, value: ds.lotid, direction: ParameterDirection.Input);
                param.Add("p_option", dbType: DbType.String, value: ds.option, direction: ParameterDirection.Input);
                param.Add("p_ostype", dbType: DbType.String, value: ostype, direction: ParameterDirection.Input);
                return dbConnection.Query<servermasterModel>(query, param, commandType: CommandType.StoredProcedure);
            }
        }
        public static object ExecuteSP_ReturnList6(string spname, int par1, int par2, int par3, string par4, int par5, int par6, string mode)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                param.Add("outlineconfigid_p", dbType: DbType.Int32, value: par1, direction: ParameterDirection.Input);
                param.Add("parent_p", dbType: DbType.Int32, value: par2, direction: ParameterDirection.Input);
                param.Add("projectdid_p", dbType: DbType.Int32, value: par3, direction: ParameterDirection.Input);
                param.Add("stage_p", dbType: DbType.String, value: par4, direction: ParameterDirection.Input);
                param.Add("stageid_p", dbType: DbType.Int32, value: par5, direction: ParameterDirection.Input);
                param.Add("projectid_p", dbType: DbType.Int32, value: par6, direction: ParameterDirection.Input);
                // param.Add("inputjsonstr", inputjsonstring);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                var list = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).ToList();
                return list;
            }
        }
        public static void WriteLog(string logtxt, string method)
        {
            try
            {
                string d = System.IO.Directory.GetCurrentDirectory();
                using (StreamWriter writer = new StreamWriter(d + "\\log.log.txt", true))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("------------------------ Log start----------------------------");
                    sb.AppendLine("Date:-" + DateTime.Now.ToString());
                    sb.AppendLine("Method Name :" + method);
                    sb.AppendLine("Log Message :" + logtxt);
                    sb.AppendLine("------------------------ Log End----------------------------");
                    writer.WriteLine(sb.ToString());
                    writer.Close();
                    // tw.WriteLine("The next line!");
                };
            }
            catch (Exception)
            {
            }
            //System.IO.File.WriteAllText(d+"\\error.log.txt", sb.ToString());
        }

        public static int addlog(object data, string mastername)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    string input = JsonConvert.SerializeObject(data);
                    int result = 0;
                    string query = @"public.sp" + mastername;
                    var param = new DynamicParameters();
                    param.Add("inputjsonstr", dbType: DbType.String, value: input, direction: ParameterDirection.Input);
                    param.Add("mode_p", dbType: DbType.String, value: "insert", direction: ParameterDirection.Input);
                    result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();
                    return result;
                }
            }
            catch (Exception)
            {
                return 0;
            }
        }
        public static string GetServerPathbatchWithStage(string lotid, string batchid, string stagename, string option, bool createdir = false)
        {
            Console.WriteLine("IOService:GetServerPathbatch:lotid" + lotid);
            Console.WriteLine("IOService:GetServerPathbatch:batchid" + batchid);
            string serverpath = string.Empty;
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                    if (isWindows)
                    {
                       
                        var data = new { p_lotid = lotid, p_batchid = batchid, p_stagename = stagename, p_option = option, p_ostype = "Windows" };
                        var jsonstr = JsonConvert.SerializeObject(data);
                        Console.WriteLine("Param:jsonstr" + jsonstr);
                        var res = CommonRepository.ExecuteSP_ReturnList1("spusrserverpathinfobatch", jsonstr);

                        var data1 = JsonConvert.DeserializeObject<object>(res.ToString());
                        JArray NextStage = JArray.Parse(data1.ToString());
                        serverpath = NextStage[0]["serverpath"].ToString();

                        if (createdir)
                        {
                            Directory.CreateDirectory(Path.Combine(serverpath, "IN"));
                            Directory.CreateDirectory(Path.Combine(serverpath, "OUT"));
                        }
                    }
                    else
                    {
                        var data = new { p_lotid = lotid, p_batchid = batchid, p_stagename = stagename, p_option = option, p_ostype = "Linux" };
                        var jsonstr = JsonConvert.SerializeObject(data);
                        Console.WriteLine("Param:jsonstr" + jsonstr);
                        var res = CommonRepository.ExecuteSP_ReturnList1("spusrserverpathinfobatch", jsonstr);

                        var data1 = JsonConvert.DeserializeObject<object>(res.ToString());
                        JArray NextStage = JArray.Parse(data1.ToString());
                        serverpath = NextStage[0]["serverpath"].ToString();
                        
                        if (createdir)
                        {
                            Directory.CreateDirectory(Path.Combine(serverpath, "IN"));
                            Directory.CreateDirectory(Path.Combine(serverpath, "OUT"));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return serverpath;
            }
            return serverpath;
        }
        public static string GetServerPathbatch(string lotid, Int32 batchid, bool createdir = false, string serverinfo = "")
        {
            Console.WriteLine("IOService:GetServerPathbatch:lotid" + lotid);
            Console.WriteLine("IOService:GetServerPathbatch:batchid" + batchid);
            Console.WriteLine("IOService:GetServerPathbatch:serverinfo" + serverinfo);
            string serverpath = string.Empty;
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                    if (isWindows)
                    {
                        dbConnection.Open();
                        var param = new DynamicParameters();
                        const string query = @"public.spusrserverpathinfobatch";
                        param.Add("p_lotid", dbType: DbType.Int32, value: Convert.ToInt32(lotid), direction: ParameterDirection.Input);
                        param.Add("p_batchid", dbType: DbType.Int32, value: Convert.ToInt32(batchid), direction: ParameterDirection.Input);
                        param.Add("p_option", dbType: DbType.String, value: serverinfo, direction: ParameterDirection.Input);
                        param.Add("p_ostype", dbType: DbType.String, value: "Windows", direction: ParameterDirection.Input);
                        IEnumerable<servermasterModel> sm = dbConnection.Query<servermasterModel>(query, param, commandType: CommandType.StoredProcedure);
                        if (createdir)
                        {
                            serverpath = FormatPath(sm.First().serverpath.ToString());
                            Directory.CreateDirectory(Path.Combine(serverpath, "IN"));
                            Directory.CreateDirectory(Path.Combine(serverpath, "OUT"));
                        }
                        else
                        {
                            serverpath = FormatPath(sm.First().serverpath.ToString());
                        }
                    }
                    else
                    {
                        dbConnection.Open();
                        var param = new DynamicParameters();
                        const string query = @"public.spusrserverpathinfobatch";
                        param.Add("p_lotid", dbType: DbType.Int32, value: Convert.ToInt32(lotid), direction: ParameterDirection.Input);
                        param.Add("p_batchid", dbType: DbType.Int32, value: Convert.ToInt32(batchid), direction: ParameterDirection.Input);
                        param.Add("p_option", dbType: DbType.String, value: serverinfo, direction: ParameterDirection.Input);
                        param.Add("p_ostype", dbType: DbType.String, value: "Linux", direction: ParameterDirection.Input);
                        IEnumerable<servermasterModel> sm = dbConnection.Query<servermasterModel>(query, param, commandType: CommandType.StoredProcedure);
                        if (createdir)
                        {
                            serverpath = sm.First().serverpath.ToString();
                            Directory.CreateDirectory(Path.Combine(serverpath, "IN"));
                            Directory.CreateDirectory(Path.Combine(serverpath, "OUT"));
                        }
                        else
                        {
                            serverpath = sm.First().serverpath.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return serverpath;
            }
            return serverpath;
        }
        public static string FormatPath(string inputpath)
        {
            try
            {
                inputpath = inputpath.Replace("/", "\\");
                inputpath = inputpath.Replace("\\\\", "");
                inputpath = System.Text.RegularExpressions.Regex.Replace(inputpath, @"\\\\", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            return string.Concat("\\\\", inputpath);
        }

    }
}
