using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Diagnostics;
using System.IO;
using Newtonsoft.Json.Linq;
using LAPS_WATCHER.Models;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Configuration;
using LAPS_WATCHER.Configure;
using RequestService.KLI_IOService;
using System.Net.Mail;
using System.Net;
//using Ionic.Zip;

namespace LAPS_WATCHER.App_Data
{
    static class CommonClass
    {
        public static List<appdetails> CheckAppType(string tranid, string userid)
        {
            appdetails appdetails = new appdetails();
            //appdetails obj = null;
            List<appdetails> appdetails1 = new List<appdetails>();
            insertcomments oInsertComments = new insertcomments();
            oInsertComments.tranid = Convert.ToUInt32(tranid);
            oInsertComments.userid = Convert.ToUInt32(userid);
            oInsertComments.status = "R";
            oInsertComments.p_option = "apptype";
            var input = JsonConvert.SerializeObject(oInsertComments);
            var appType = CommonRepository.ExecuteSP_ReturnList1("spusrlottransactionupdate", input);
            if (appType != null)
            {
                var i_appType = JsonConvert.DeserializeObject<object>(appType.ToString());
                JArray a_appType = JArray.Parse(i_appType.ToString());
                JObject obj_appType = JObject.Parse(a_appType[0].ToString());
                appdetails.jobworkflowid = obj_appType["jobworkflowid"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["jobworkflowid"].ToString());
                appdetails.lotid = obj_appType["lotid"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["lotid"].ToString());
                appdetails.jobid = obj_appType["jobid"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["jobid"].ToString());
                appdetails.merged_lot = obj_appType["merged_lot"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["merged_lot"].ToString());
                appdetails.batchid = obj_appType["batchid"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["batchid"].ToString());
                appdetails.nextstage = obj_appType["nextstage"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["nextstage"].ToString());
                appdetails.movebackstage = obj_appType["movebackstage"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["movebackstage"].ToString());
                appdetails.stagetype = obj_appType["stagetype"].ToString();
                appdetails.process_without_file = obj_appType["process_without_file"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["process_without_file"].ToString());
                appdetails.checkin_app = obj_appType["checkin_app"].ToString();
                appdetails.inprocessapp = obj_appType["inprocessapp"].ToString();
                appdetails.checkout_app = obj_appType["checkout_app"].ToString();
                appdetails.exe_path = obj_appType["exepath"].ToString();

                appdetails.checkin_appwather = obj_appType["checkin_appwather"].ToString();
                appdetails.inprocessappwatcher = obj_appType["inprocessappwatcher"].ToString();
                appdetails.checkout_appwatcher = obj_appType["checkout_appwatcher"].ToString();
                appdetails.ipaexepath = obj_appType["ipaexepath"].ToString();
                appdetails.coaexepath = obj_appType["coaexepath"].ToString();
                appdetails.is_checkin_exe = obj_appType["is_checkin_exe"].ToString();
                appdetails.ciaisservice = obj_appType["ciaisservice"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["ciaisservice"].ToString());
                appdetails.ipaisservice = obj_appType["ipaisservice"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["ipaisservice"].ToString());
                appdetails.coaisservice = obj_appType["coaisservice"].ToString() == "" ? 0 : Convert.ToInt32(obj_appType["coaisservice"].ToString());
            }
            appdetails1.Add(appdetails);
            return appdetails1;

        }
        public static string CopyDirectory(string sourceDir, string destinationDirc)
        {
            string Name = "";
            DirectoryInfo source = new DirectoryInfo(sourceDir);
            DirectoryInfo destination = new DirectoryInfo(destinationDirc);
            if (!destination.Exists)
            {
                destination.Create();
            }
            if (!source.Exists)
            {
                return "erorr";
            }
            FileInfo[] files = source.GetFiles();
            foreach (FileInfo file in files)
            {
                if (file.Name.ToLower().Trim() != "thumbs.db")
                {
                    Name = file.Name;
                    string Dest = System.IO.Path.Combine(destination.FullName, file.Name);
                    if (System.IO.File.Exists(Dest))
                    {
                        System.IO.File.Delete(Dest);
                    }
                    if (!System.IO.File.Exists(Dest))
                    {
                        file.CopyTo(Dest, true);
                    }
                }
            }
            DirectoryInfo[] dirs = source.GetDirectories();
            foreach (DirectoryInfo dir in dirs)
            {
                string destinationDir = System.IO.Path.Combine(destination.FullName, dir.Name);
                string destinationDir1 = dir.FullName;
                CopyDirectory(destinationDir1, destinationDir);
            }
            return Name;
        }

        public static string MoveDirectory(string sourceDir, string destinationDirc)
        {
            string Name = "";
            DirectoryInfo source = new DirectoryInfo(sourceDir);
            DirectoryInfo destination = new DirectoryInfo(destinationDirc);
            if (!destination.Exists)
            {
                destination.Create();
            }
            if (!source.Exists)
            {
                return "erorr";
            }
            FileInfo[] files = source.GetFiles();
            foreach (FileInfo file in files)
            {
                if (file.Name.ToLower().Trim() != "thumbs.db")
                {
                    Name = file.Name;
                    string Dest = System.IO.Path.Combine(destination.FullName, file.Name);
                    if (System.IO.File.Exists(Dest))
                    {
                        System.IO.File.Delete(Dest);
                    }
                    if (!System.IO.File.Exists(Dest))
                    {
                        file.MoveTo(Dest);
                    }
                }
            }
            DirectoryInfo[] dirs = source.GetDirectories();
            foreach (DirectoryInfo dir in dirs)
            {
                string destinationDir = System.IO.Path.Combine(destination.FullName, dir.Name);
                string destinationDir1 = dir.FullName;
                CopyDirectory(destinationDir1, destinationDir);
            }
            return Name;
        }
        public static 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 static void laps2Log(string func, string logtext)
        {
            try
            {

                //string d = System.IO.Directory.GetCurrentDirectory();
                string d = System.IO.Directory.GetCurrentDirectory();
                using (StreamWriter writer = new StreamWriter(d + "\\laps2log.log.txt", true))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("------------------------ Log start----------------------------");
                    sb.AppendLine("Date:-" + DateTime.Now.ToString());
                    sb.AppendLine("Application Name :" + func);
                    sb.AppendLine("Error Message :" + logtext);
                    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 void WriteLog(string fileName, string MSGID, string Log)
        {
            TextWriter tw = new StreamWriter(fileName, append: true);
            tw.WriteLine("---------------------------------");
            tw.WriteLine("Message ID : " + MSGID + " Date : " + DateTime.Now.ToString());
            tw.WriteLine(Log.ToString());
            tw.WriteLine("---------------------------------");
            tw.Close();
        }
        public static string GetBackupfolder(string pathfold)
        {
            try
            {
                int i = 1;
            rechck:;
                string folderprefix = "\\V";
                bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                if (isWindows)
                { folderprefix = "\\V"; }
                else
                {
                    folderprefix = "/V";
                }

                    if (Directory.Exists(string.Join("", pathfold, folderprefix, i.ToString("000"))))
                {
                    i++;
                    goto rechck;
                }
                else
                {
                    Directory.CreateDirectory(string.Join("", pathfold, folderprefix, i.ToString("000")));
                    //Directory.CreateDirectory(string.Join("", pathfold, "\\V", i.ToString("000")) + "\\OUT");
                    return pathfold + folderprefix + i.ToString("000");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                //ErrorLogger.environment = enviroment; ErrorLogger.errorLog.WriteErrorLog(new ErrorTranslate { TranID = Convert.ToInt64(tranid), ErrorMessage = ex.Message.ToString() });
                return pathfold;
            }
        }
        public static string ErrorMsg = "", PrcOut = "";
        public static string ExecComp(string AppName, string Params, string basedir = null)
        {
            Console.WriteLine("LAPS2 App Watcher: ExecComp " + "ExecComp:AppName " + AppName + "Params: " + Params, "CommonClass ");
           
            try
            {
                Type callType = Type.GetType(AppName);
                callType.GetMethod("call_kli_ioservice").Invoke(null, new[] { Params });
                //typeof(kli_ioservice).GetMethod("call_kli_ioservice").Invoke(null, new[] { Params });

            }
            catch (Exception exp)
            {
                Console.WriteLine("LAPS2 App Watcher:ExecComp:Error, exception is" + exp.Message + "::" + exp.StackTrace);
                CommonClass.ErrorLog(exp);
                ErrorMsg = "Error while conversion, exception is: " + exp.Message + "::" + exp.StackTrace;
            }
            finally { /*if (compare != null) compare.Close();*/ }
            return ErrorMsg;
        }

        public static string ExecCompwatcher(string AppName, string Params, string basedir = null)
        {
            Process compare = new Process();
            try
            {

                compare.StartInfo.FileName = AppName;
                compare.StartInfo.Arguments = Params;
                compare.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                compare.StartInfo.WorkingDirectory = Path.GetDirectoryName(AppName);
                compare.Start();
                compare.WaitForExit();


                //Process Prc = null;
                //try
                //{
                //    Prc = new Process();
                //    Prc.StartInfo.FileName = AppName;
                //    Prc.StartInfo.Arguments = Params;
                //    //////Prc.StartInfo.UserName = "ldl\\ssgchn";
                //    //////var secure = new SecureString();
                //    //////foreach (char c in "$sgs$426") { secure.AppendChar(c); }
                //    //////Prc.StartInfo.Password = secure;
                //    Prc.StartInfo.CreateNoWindow = true;
                //    Prc.StartInfo.UseShellExecute = false;
                //    Prc.Exited += Prc_Extd;
                //    Prc.StartInfo.RedirectStandardError = true;
                //    Prc.StartInfo.RedirectStandardOutput = true;
                //    Prc.ErrorDataReceived += new DataReceivedEventHandler(Prc_ErDtRcvd);
                //    Prc.OutputDataReceived += new DataReceivedEventHandler(Prc_OpDtRcvd);
                //    Prc.Start();
                //    Prc.BeginErrorReadLine();
                //    Prc.BeginOutputReadLine();
                //    Prc.WaitForExit();
                if (ErrorMsg != "") return ErrorMsg;
                Console.WriteLine(ErrorMsg);
            }
            catch (Exception exp) { ErrorMsg = "Error while conversion, exception is: " + exp.Message + "::" + exp.StackTrace; }
            finally { if (compare != null) compare.Close(); }
            return ErrorMsg;
            //Console.WriteLine("LAPS2 App Watcher: ExecCompwatcher " + "ExecCompwatcher:AppName " + AppName + "Params: " + Params, "CommonClass ");

            //try
            //{
            //    Type callType = Type.GetType(AppName);
            //    callType.GetMethod("call_kli_ioservice").Invoke(null, new[] { Params });
            //    //typeof(kli_ioservice).GetMethod("call_kli_ioservice").Invoke(null, new[] { Params });

            //}
            //catch (Exception exp)
            //{
            //    Console.WriteLine("LAPS2 App Watcher:ExecComp:Error, exception is" + exp.Message + "::" + exp.StackTrace);
            //    CommonClass.ErrorLog(exp);
            //    ErrorMsg = "Error while conversion, exception is: " + exp.Message + "::" + exp.StackTrace;
            //}
            //finally { /*if (compare != null) compare.Close();*/ }
            //return ErrorMsg;
        }
        private static void Prc_Extd(object sender, EventArgs e) { /* PrcRv += ShowMsg("process completed!"); */ }
        private static void Prc_ErDtRcvd(object sender, DataReceivedEventArgs e) { if (e.Data != null && e.Data != "") { ErrorMsg += "\r\n" + e.Data; } }
        private static void Prc_OpDtRcvd(object sender, DataReceivedEventArgs e) { if (e.Data != null && e.Data != "") { PrcOut += "\r\n" + e.Data; } }

        public static void WriteLog(string logtxt, string method)
        {
            try
            {

                string d = System.IO.Directory.GetCurrentDirectory();
                using (StreamWriter writer = new StreamWriter(d + "\\laps2log.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 void CreateZip(string directoryPathToZip, string outputZipFileName)
        //{
        //    try
        //    {
        //        if (File.Exists(outputZipFileName))
        //        {
        //            File.Delete(outputZipFileName);
        //        }
        //        using (ZipFile outputZip = new ZipFile(outputZipFileName))
        //        {
        //            outputZip.AddDirectory(directoryPathToZip);
        //            outputZip.Save();
        //        }
        //    }
        //    catch (Exception ex)
        //    { Console.WriteLine(ex.Message.ToString()); }
        //}

        public static void SendMail(string tomail, StringBuilder sbody, StringBuilder ssubject)
        {
            try
            {
                SmtpClient smtpClient = new SmtpClient();
                MailAddress fromAddress = null;
                using (MailMessage message = new MailMessage())
                {
                    string b = WebUtility.HtmlDecode(sbody.ToString());
                    message.Body = b;
                    message.Subject = ssubject.ToString();
                    message.To.Add(new MailAddress(tomail));
                    fromAddress = new MailAddress(CustomConfiguration.AppSettings["AppSettings:emailusername"], "KLI DEV");
                    smtpClient.Host = CustomConfiguration.AppSettings["AppSettings:emailhost"];
                    smtpClient.EnableSsl = true;
                    smtpClient.Port = Convert.ToInt32(CustomConfiguration.AppSettings["AppSettings:emailportid"]);
                    NetworkCredential myCredential = new NetworkCredential(CustomConfiguration.AppSettings["AppSettings:emailusername"],
                        CustomConfiguration.AppSettings["AppSettings:emailpassword"]);
                    smtpClient.Credentials = myCredential;
                    message.From = fromAddress;
                    MailMessage mail = new MailMessage();
                    message.IsBodyHtml = true;
                    smtpClient.Send(message);
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine("LAPS2 App Watcher:SendMail:Error, exception is" + exp.Message + "::" + exp.StackTrace);
                CommonClass.ErrorLog(exp);
            }
        }
        public class insertcomments
        {
            public long transid { set; get; }
            public string comment { set; get; }
            public string doption { set; get; }
            public string tostage { set; get; }
            public long jobid { set; get; }
            public long lotid { set; get; }
            public string filename { set; get; }
            public string lotstatus { set; get; }
            public long userid { set; get; }
            public string status { set; get; }
            public string comments { set; get; }
            public long jobworkflowid { set; get; }
            public long tranid { set; get; }
            public string transactionkey { set; get; }
            public string p_option { set; get; }

        }
    }
}
