using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace Console_SendMail
{
    partial class Program
    {
        //DateTime redisTryTime = DateTime.Parse("1982-11-23");
        static Boolean bBW = true;
        static DateTime ChkMakeAutoTime = DateTime.Now.AddDays(-1);
        static DateTime ChkSendMailTime = DateTime.Now.AddDays(-1);
        static DateTime ChkMakeSchDayWeekTime = DateTime.Now.AddDays(-1);
        static DateTime ChkMakePrjUpdateWeekTime = DateTime.Now.AddDays(-1);
        static DateTime ChkMakeSchDay = DateTime.Now.AddDays(-1);
        static DateTime ChkNoSchedule = DateTime.Now.AddDays(-1);
        static DateTime ChkJobreportDay = DateTime.Now.AddDays(-1);
        static DateTime ChkJObreportWeek = DateTime.Now.AddDays(-1);
        static DateTime ChkTakeARest = DateTime.Now.AddDays(-1);

        public static string MailSort(string addr, string except)
        {
            if (string.IsNullOrEmpty(except)) return addr;
            var alist = addr.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var elist = except.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            foreach (var item in elist)
                alist.Remove(item);
            if (alist.Count < 1) return string.Empty;
            return string.Join(";", alist);
        }

        static string getdbdata(object tdata)
        {
            if (tdata == null) return string.Empty;
            return tdata.ToString();
        }
        static string getMaillist(object orgo)
        {
            var org = string.Empty;
            if (orgo != null) org = orgo.ToString();
            org = org.Replace(";", ",").Replace(":", ",");
            string list_to = "";
            foreach (var item in org.Split(','))
            {
                if (item.Trim() != "")
                {
                    var atindex = item.IndexOf("@");
                    if (atindex != -1)
                    {
                        var dotindex = item.IndexOf(".", atindex + 1);
                        if (dotindex != -1)
                        {
                            //정상이므로 추가한다.
                            if (list_to != "") list_to += ",";
                            list_to += item.Trim();
                        }
                    }
                }
            }
            return list_to;
        }
        //static void Main(string[] args)
        //{
        //    //var mc = new System.Net.Mail.SmtpClient("k5lexim01.kr.ds.amkor.com");
        //    //mc.Credentials = new System.Net.NetworkCredential("bookmanager", "BIDA19R=maga2#H9gY[JPx%~M^NyIG");
        //    //var msg = new System.Net.Mail.MailMessage("bookmanager@amkor.co.kr", "chikyun.kim@amkor.co.kr");
        //    //msg.Body = "test";
        //    //msg.Subject = "test mail";
        //    //try
        //    //{
        //    //    mc.Send(msg);
        //    //    Console.WriteLine(  "ok");
        //    //    Console.ReadLine();
        //    //    Console.ReadKey();
        //    //}catch ( Exception ex)
        //    //{
        //    //    Console.WriteLine( ex.Message);
        //    //}

        //    Chilkat.MailMan mailman = new Chilkat.MailMan();
        //    bool success = mailman.UnlockComponent("GAMACM.CB8082024_Tz2XiNck4U5N");
        //    if(success ==false ) Console.WriteLine("license errr" );
        //    mailman.SmtpHost = "k5lexim01.kr.ds.amkor.com";
        //    mailman.SmtpPort = 25;

        //    mailman.SmtpUsername = "bookmanager";
        //    mailman.SmtpPassword = "BIDA19R=maga2#H9gY[JPx%~M^NyIG";

        //    Chilkat.Email email = new Chilkat.Email();
        //    email.Subject = "test";
        //    email.SetHtmlBody("test");
        //    email.From = "bookmanager@amkor.co.kr";
        //    email.AddTo("chikyun", "chikyun.kim@amkor.co.kr");

        //    success = mailman.SendEmail(email);
        //    if (success != true)
        //    {
        //        Console.WriteLine("메일 발송 실패");                
        //    }
        //    else Console.WriteLine( "ok");
        //        success = mailman.CloseSmtpConnection();
        //}

        static void Main(string[] args)
        {




            //var mc = new System.Net.Mail.SmtpClient("k5lexim01.kr.ds.amkor.com");
            //mc.Credentials = new System.Net.NetworkCredential("bookmanager", "BIDA19R=maga2#H9gY[JPx%~M^NyIG");
            //var msg = new System.Net.Mail.MailMessage("chikyun.kim@amkor.co.kr", "chikyun.kim@amkor.co.kr");
            //msg.Body = "test";
            //msg.Subject = "test mail";
            //mc.Send(msg);





            // 명령행 인수 처리
            if (args.Length > 0)
            {
                string command = args[0].ToLower();
                switch (command)
                {
                    case "-install":
                    case "/install":
                        InstallService();
                        return;
                    case "-uninstall":
                    case "/uninstall":
                        UninstallService();
                        return;
                    case "-console":
                    case "/console":
                        RunAsConsole();
                        return;
                    case "-help":
                    case "/help":
                    case "/?":
                        ShowHelp();
                        return;
                }
            }

            // 서비스로 실행
            if (Environment.UserInteractive)
            {
                // 대화형 모드에서는 콘솔로 실행
                RunAsConsole();
            }
            else
            {
                // 서비스로 실행
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new MailService() 
                };
                ServiceBase.Run(ServicesToRun);
            }
        }

        private static void ShowHelp()
        {
            Console.WriteLine("EETGW Mail Service");
            Console.WriteLine("사용법:");
            Console.WriteLine("  Console_SendMail.exe               - 서비스로 실행");
            Console.WriteLine("  Console_SendMail.exe -console      - 콘솔 모드로 실행");
            Console.WriteLine("  Console_SendMail.exe -install      - 서비스 설치");
            Console.WriteLine("  Console_SendMail.exe -uninstall    - 서비스 제거");
            Console.WriteLine("  Console_SendMail.exe -help         - 도움말 표시");
        }

        private static void InstallService()
        {
            try
            {
                string servicePath = $"\"{System.Reflection.Assembly.GetExecutingAssembly().Location}\"";
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "sc.exe",
                    Arguments = $"create EETGWMailService binPath= \"{servicePath}\" DisplayName= \"EETGW Mail Service\" start= auto",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                };

                using (Process process = Process.Start(startInfo))
                {
                    process.WaitForExit();
                    if (process.ExitCode == 0)
                    {
                        Console.WriteLine("서비스가 성공적으로 설치되었습니다.");
                        Console.WriteLine("서비스를 시작하려면 다음 명령을 실행하세요:");
                        Console.WriteLine("net start EETGWMailService");
                    }
                    else
                    {
                        string error = process.StandardError.ReadToEnd();
                        Console.WriteLine($"서비스 설치 실패: {error}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"서비스 설치 중 오류 발생: {ex.Message}");
            }
        }

        private static void UninstallService()
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "sc.exe",
                    Arguments = "delete EETGWMailService",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                };

                using (Process process = Process.Start(startInfo))
                {
                    process.WaitForExit();
                    if (process.ExitCode == 0)
                    {
                        Console.WriteLine("서비스가 성공적으로 제거되었습니다.");
                    }
                    else
                    {
                        string error = process.StandardError.ReadToEnd();
                        Console.WriteLine($"서비스 제거 실패: {error}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"서비스 제거 중 오류 발생: {ex.Message}");
            }
        }

        private static void RunAsConsole()
        {
            // 중복실행 방지 체크
            if (!CheckSingleInstance())
            {
                return; // 프로그램 종료
            }

            Console.WriteLine($"mail start ver 2508051140 (콘솔 모드)");
            Console.WriteLine("종료하려면 Ctrl+C를 누르세요.");
            
            // Ctrl+C 핸들러 설정
            Console.CancelKeyPress += (sender, e) =>
            {
                Console.WriteLine("\n메일 서비스를 종료합니다...");
                e.Cancel = false;
            };

            try
            {
                while (true)
                {
                    ExecuteMailOperations();
                    Thread.Sleep(1000); // 1초 대기
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"오류 발생: {ex.Message}");
            }
            finally
            {
                Console.WriteLine("mail end");
            }
        }

        /// <summary>
        /// 메일 관련 작업들을 실행하는 메서드 (서비스와 콘솔에서 공통 사용)
        /// </summary>
        public static void ExecuteMailOperations()
        {
            //메일대기내역전송
            var tsSendMail = DateTime.Now - ChkSendMailTime;
            if (tsSendMail.TotalMilliseconds > 1000)
            {
                try { SendMail(); }
                catch { }
                finally { ChkSendMailTime = DateTime.Now; }
            }

            //자동생성 메일 작성
            var tsAutoMake = DateTime.Now - ChkMakeAutoTime;
            if (tsAutoMake.TotalMinutes >= 10)
            {
                try { MakeAutoMail(); }
                catch { }
                finally { ChkMakeAutoTime = DateTime.Now; }
            } 
            
            //프로젝트업데이트알림
            var tsPrjUpdateweek = DateTime.Now - ChkMakePrjUpdateWeekTime;
            if (tsPrjUpdateweek.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18)
            {
                try { Mail_MakeUpdateRequireProject(); }
                catch { }
                finally { ChkMakePrjUpdateWeekTime = DateTime.Now; }
            }

            ///스케쥴 기한 알림(주)
            var tsScheDayweek = DateTime.Now - ChkMakeSchDayWeekTime;
            if (tsScheDayweek.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18)
            {
                try { Mail_MakeScheduleDayWeek(); }
                catch { }
                finally { ChkMakeSchDayWeekTime = DateTime.Now; }
            }
          
            ///스케쥴 기한 알림(일)
            var tsScheDay = DateTime.Now - ChkMakeSchDay;
            if (tsScheDay.TotalMinutes > 30 && DateTime.Now.DayOfWeek != DayOfWeek.Saturday &&
                DateTime.Now.DayOfWeek != DayOfWeek.Sunday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18)
            {
                try { Mail_MakeScheduleDay(); }
                catch { }
                finally { ChkMakeSchDay = DateTime.Now; }
            }

            ///스케쥴없음
            var tsNoSchedule = DateTime.Now - ChkNoSchedule;
            if (tsNoSchedule.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 18)
            {
                try { Mail_NoSchedule(); }
                catch { }
                finally { ChkNoSchedule = DateTime.Now; }
            }

            ///업무일지(주간)
            var tsjobweek = DateTime.Now - ChkJObreportWeek;
            if (tsjobweek.TotalMinutes > 30 && DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 18)
            {
                try { Mail_JobReportWeek(); }
                catch { }
                finally { ChkJObreportWeek = DateTime.Now; }
            }

            ///업무일지(일)
            var tsjobday = DateTime.Now - ChkJobreportDay;
            if (tsjobday.TotalMinutes > 15 &&
                DateTime.Now.DayOfWeek != DayOfWeek.Saturday &&
                DateTime.Now.DayOfWeek != DayOfWeek.Sunday &&
                DateTime.Now.DayOfWeek != DayOfWeek.Monday &&
                DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 18)
            {
                try { Mail_JobReportDay(); }
                catch { }
                finally { ChkJobreportDay = DateTime.Now; }
            }

            ///휴가신청(Remind) - 230611
            var tsTakeaRest = DateTime.Now - ChkTakeARest;
            if (tsTakeaRest.TotalMinutes > 15 &&
                DateTime.Now.DayOfWeek != DayOfWeek.Saturday &&
                DateTime.Now.DayOfWeek != DayOfWeek.Sunday &&
                DateTime.Now.Hour >= 17)
            {
                try { Mail_Take_a_rest_remind(); }
                catch { }
                finally { ChkTakeARest = DateTime.Now; }
            }
        }

        /// <summary>
        /// 중복실행 방지 체크
        /// </summary>
        /// <returns>단일 인스턴스인 경우 true, 중복실행인 경우 false</returns>
        static bool CheckSingleInstance()
        {
            string processName = Process.GetCurrentProcess().ProcessName;
            Process[] processes = Process.GetProcessesByName(processName);

            if (processes.Length > 1)
            {
                // 중복실행 감지
                string message = $"⚠️ 프로그램이 이미 실행 중입니다!\n\n" +
                                "동시에 여러 개의 프로그램을 실행할 수 없습니다.\n\n" +
                                "해결방법을 선택하세요:";

                Console.WriteLine(message);
                    // 현재 실행을 취소
                    return false;
                
            }

            return true; // 단일 인스턴스
        }
    }
}
