using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Diagnostics;

// 2015.8.20
// 시운전하고 , 프로젝트를 관리하는 사람들이 사용하도록 프로그램을 구성한다
// 닷넷프레임워크는 2.0 (이전 버전도 적용해야되므로)
// 1. 현재 동작중인 프로그램 종료
// 2. 이벤트로그 데이타 삭제
// 3. 레지스트리값에 최신 작업내역을 쓰고, 세부 내용은 별도의 텍스트 로그로 남겨놓는다

// 2016.11.24
// 수신기 형식 인증을 위해 아래와 같이 프로그램을 준비한다
// 시운전프로그램 준비 -> 동글인식해야 프로그램가동 + 데이타베이스 교체 -> 로그인 (사용자계정이 별도로 있음) -> 사유기록-> 사용기록파일을 남기도록 함

// 2016.11.29
// 동글키를 인식하기 위한 dll 은 Ry4SCom.dll 이다. CIL  을 이용하는 것같다. 반드시 regsvr32 명령을 이용해 CLR 등록하도록 한다
namespace IControls_FireManager
{
    public partial class Main : Form
    {
        // 타이머 카운터
        int MainTimerTick_Cnt = 0;
        
        // 로그인 정보
        string User = null;

        // 폴더 정보
        string Receiver_Project_Path = null; // Receiver1 
        string Usb_Update_Path = Environment.CurrentDirectory + "\\Update"; 

        // 로그 내용
        string txt = null;

        public Main(string UserID)
        {
            InitializeComponent();

            User = UserID;

            // 참고 : 라디오버튼 그룹핑은 tapstop -> true~false 로 이용하면 됨
            // 이벤트로그삭제는 전체 삭제가 기본값
            this.radioButton_EventLogDel_All.Checked = true;

            try
            {
                // 레지스트리값 읽기
                RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\I_FPER_COMM_DAEMON", false);
                string Temp_DATABASE_NAME = rk.GetValue("DATABASE_NAME").ToString();
                string Registry_DATABASE_NAME = Temp_DATABASE_NAME;
                string Registry_DATABASE_NAME_IP = Temp_DATABASE_NAME.Substring(0, Temp_DATABASE_NAME.IndexOf(":"));
                string Registry_DATABASE_NAME_PATH = Temp_DATABASE_NAME.Substring(Temp_DATABASE_NAME.IndexOf(":") + 1);
                string Registry_Project_Directory = rk.GetValue("PROJECT_DIR").ToString();
                _Db.DB_FullPath = Registry_DATABASE_NAME_PATH;            
            }
            catch
            {
                ;
            }
        }

        // 이벤트 로그 삭제 여부
        private void checkBox_EventLogDel_CheckedChanged(object sender, EventArgs e)
        {
            this.radioButton_EventLogDel_All.Enabled = this.radioButton_EventLogDel_Day.Enabled = this.checkBox_EventLogDel.Checked;
            this.dateTimePicker1.Enabled = this.dateTimePicker2.Enabled = this.radioButton_EventLogDel_Day.Checked;
        }

        // 시간지정시에만 활성화
        private void radioButton_EventLogDel_Day_CheckedChanged(object sender, EventArgs e)
        {
            this.dateTimePicker1.Enabled = this.dateTimePicker2.Enabled = this.radioButton_EventLogDel_Day.Checked;
        }

        // 시작 버튼을 누름
        private void button_Start_Click(object sender, EventArgs e)
        {   
            // 로그 내용           
            txt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " [" + User + "] \r\n";
            
            if (this.textBox_Comment.Text.Trim().Length == 0)
            {
                MessageBox.Show("반드시 사유를 입력 하셔야됩니다");
                return;
            }
            
            if (this.checkBox_FileUpdate.Checked == false && this.checkBox_EventLogDel.Checked == false)
            { 
                MessageBox.Show("최소한 하나 이상은 선택하셔야됩니다");
                return;
            }

            txt = txt + string.Format(" 사유 : {0}\r\n", this.textBox_Comment.Text);

            // 만약 파일업데이트가 체크되어있다면 실행파일 경로에 반드시 DB 파일이나 실행파일이 존재해야한다.
            if (this.checkBox_FileUpdate.Checked == true)
            {
                string[] files = Directory.GetFiles(Usb_Update_Path);
                string[] folders = Directory.GetDirectories(Usb_Update_Path);
                
                if (files.Length == 0 && folders.Length == 0)
                { MessageBox.Show("업데이트 파일이 존재하지 않습니다"); return; }
            }

            // 타이머 동작
            MainTimerTick_Cnt = 0;
            _Timer_WindowBase.Delete("Main_Timer");
            _Timer_WindowBase.Create("Main_Timer", 1000, Main_Timer_Tick, true);
        }
       
        // 타이머 
        private void Main_Timer_Tick(object sender, EventArgs e)
        {
            try
            {
                // UI 갱신
                this.label_Status.Text = string.Format("진행상황 : {0} 초 남았습니다.", 35 - MainTimerTick_Cnt);

                // 카운터 증사
                MainTimerTick_Cnt++;

                // 카운터별 동작
                switch (MainTimerTick_Cnt)
                {
                    // 비활성화
                    case 1:
                        this.checkBox_EventLogDel.Enabled = false;
                        this.checkBox_FileUpdate.Enabled = false;
                        this.checkBox_restart.Enabled = false;
                        this.textBox_Comment.Enabled = false;
                        this.button_Start.Enabled = false;
                        break;
                    // 런쳐 종료
                    case 2:
                        if (_Diagnostics.Process_Excute("FLauncher") == true)
                            _Diagnostics.Process_Delete("FLauncher", false);
                        break;
                    // 수신기 UI 프로그램 종료
                    case 4:
                        if (_Diagnostics.Process_Excute("FPER") == true)
                            _Diagnostics.Process_Delete("FPER", false);
                        break;
                    // 데몬 종료
                    case 7:
                        if (_Diagnostics.Process_Excute("CommDaemon") == true)
                            _Diagnostics.Process_Delete("CommDaemon", false);
                        break;
                    // FireBirdLog 지우기
                    case 10:
                        string FireBirdLogPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                        FireBirdLogPath += "\\Firebird\\Firebird_2_5\\firebird.log";
                        if (File.Exists(FireBirdLogPath) == true)
                            File.Delete(FireBirdLogPath);
                        break;
                    // 레지스트리값 읽고 DB 접근자 알아낸뒤, 이벤트 로그 삭제
                    case 13:
                        // 이벤트 로그 삭제
                        if (this.checkBox_EventLogDel.Checked == true)
                        {
                            txt = txt + " EventLogDel ";
                            if (this.radioButton_EventLogDel_All.Checked == true)
                                _Db.Execute(_Sql.Delete_Table("TB_EVENT_LOG", null));
                            else
                            {   // 날짜 : 2015 08 20 00000000000 
                                //        2015 08 21 99999999999 
                                string start = this.dateTimePicker1.Value.ToShortDateString().Replace("-", "") + "00000000000";
                                string end = this.dateTimePicker2.Value.ToShortDateString().Replace("-", "") + "99999999999";
                                // 이벤트 로그 삭제
                                _Db.Execute(_Sql.DeleteEventLogDataTime(start, end));
                                // 커맨드 로그 삭제
                                _Db.Execute(_Sql.DeleteCommandLogData(start, end));
                            }
                        }
                        break;
                    // DB 폴더에 FPER.FDB 파일외에는 전부 제거
                    case 16:
                         string folder = _Db.DB_FullPath.Replace("FPER.FDB", "");
                        // DB 폴더에 접근
                        string[] files = Directory.GetFiles(folder);
                        foreach (string file in files)
                        {
                            if (_Db.DB_FullPath != file)
                            {
                                File.Delete(file);
                            }
                        }
                        break;

                    // 덮어쓰기 
                    case 19:
                        {
                            // 프로젝트 파일 경로 (Receiver1 폴더에 해당하겠다)
                            Receiver_Project_Path = _Db.DB_FullPath.Replace("DB\\FPER.FDB", "");

                            // 파일이 있는지 확인
                            string[] files_temp = Directory.GetFiles(Usb_Update_Path);
                            if (files_temp.Length != 0)
                            {   
                                Copy_Folder(Usb_Update_Path, Receiver_Project_Path);
                            }

                            // 폴더가 있는지 확인
                            string[] folders_temp = Directory.GetDirectories(Usb_Update_Path);
                            if (folders_temp.Length != 0)
                            {
                                foreach (string folders in folders_temp)
                                {
                                    string temp = Get_Folder(folders);
                                    if (temp == "DB")
                                    {
                                        string[] files_temp_db = Directory.GetFiles(Usb_Update_Path + "\\" + temp);
                                        if (files_temp_db.Length != 0)
                                        {
                                            Copy_Folder(Usb_Update_Path + "\\" + temp, Receiver_Project_Path + "\\" + temp);
                                        }
                                    }
                                    else if (temp == "mapview")
                                    {
                                        string[] folders_temp_mapview = Directory.GetDirectories(Usb_Update_Path + "\\" + temp);
                                        
                                        if (folders_temp_mapview.Length != 0)
                                        {
                                            foreach (string folders_temp_mapviews in folders_temp_mapview)                                            
                                            {
                                                string folder_name = Get_Folder(folders_temp_mapviews);
                                                Copy_Folder(Usb_Update_Path + "\\" + temp + "\\" + folder_name, Receiver_Project_Path + "\\" + temp + "\\" + folder_name);                                               
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    // 프로그램 종료
                    case 35:
                        try
                        {
                            if (this.checkBox_EventLogDel.Checked == true)
                            {
                                txt += " EventLogDel ";
                                if (this.radioButton_EventLogDel_All.Checked == true)
                                    txt += "LogDel:All";
                                else
                                    txt += "LogDel:Day[" + this.dateTimePicker1.Value.ToShortDateString() + "~" + this.dateTimePicker2.Value.ToShortDateString() + "]";
                            }
                            // 레지스트리 값에 최근 사용내역 저장
                            string history = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " >> Excute ";
                            RegistryKey Set_Rk = Registry.LocalMachine.CreateSubKey("SOFTWARE").CreateSubKey("I_FPER_COMM_DAEMON");
                            Set_Rk.SetValue("FireOperator", history);

                            // 로그를 저장하도록함         
                            Write_Log("\r\n" + txt);
                        }
                        catch
                        {
                            // 로그를 저장하도록함         
                            Write_Log("\r\n" + "레지스트리접근권한 실패");
                        }

                        // 종료후 자동으로 프로그램 재실행
                        if (this.checkBox_restart.Checked == true)
                        {
                            Process myProcess = new Process();
                            myProcess.StartInfo.WorkingDirectory = Receiver_Project_Path;
                            myProcess.StartInfo.FileName = "FLauncher.exe";                           
                            //myProcess.StartInfo.CreateNoWindow = false;
                            myProcess.Start();
                        }

                        // UI 처리완료알림
                        this.label_Status.Text = string.Format("진행상황 : 처리완료되었습니다.");
                        // 타이머 종료
                        _Timer_WindowBase.Delete("Main_Timer");
                        // 활성화
                        this.checkBox_EventLogDel.Enabled = true;
                        this.checkBox_FileUpdate.Enabled = true;
                        this.checkBox_restart.Enabled = true;
                        this.textBox_Comment.Enabled = true;
                        this.button_Start.Enabled = true;
                        break;                    

                    default:
                        if (MainTimerTick_Cnt < 0)
                        {
                            // 종료후 자동으로 프로그램 재실행
                            if (this.checkBox_restart.Checked == true)
                            {
                                Process myProcess = new Process();
                                myProcess.StartInfo.WorkingDirectory = Receiver_Project_Path;
                                myProcess.StartInfo.FileName = "FLauncher.exe";
                                //myProcess.StartInfo.CreateNoWindow = false;
                                myProcess.Start();
                            }

                            // UI 처리완료알림
                            this.label_Status.Text = string.Format("진행상황 : 처리완료되었습니다.");
                            // 타이머 종료
                            _Timer_WindowBase.Delete("Main_Timer");
                            // 활성화
                            this.checkBox_EventLogDel.Enabled = true;
                            this.checkBox_FileUpdate.Enabled = true;
                            this.checkBox_restart.Enabled = true;
                            this.textBox_Comment.Enabled = true;
                            this.button_Start.Enabled = true;
                        }
                        break;
                }



            }
            catch
            {
                ;
            }
        }

        public static void Write_Log(string txt)
        {
            try
            {
                string path = "C:\\fireguard\\Log.txt";

                if (!File.Exists(path))
                {
                    // Create a file to write to.
                    string createText = txt;// Environment.NewLine;
                    File.WriteAllText(path, createText);
                }
                else
                {
                    // This text is always added, making the file longer over time
                    // if it is not deleted.
                    string appendText = txt;
                    File.AppendAllText(path, appendText);
                }
            }
            catch
            {
                ;
            }
        }

        //  프로세스 종료 코드 추가
        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {   
            // 스레드 종료
            Application.ExitThread();

            for (int i = 0; i < 1000000; i++) { ;}

            // 프로세스 종료
            Application.Exit();

            // 프로세스가 남아있다면 최종 종료 
            System.Diagnostics.Process[] mProcess = System.Diagnostics.Process.GetProcessesByName(Application.ProductName);
            foreach (System.Diagnostics.Process p in mProcess)
                p.Kill();

            // 최종 정리 (보완코드 : 크로스 스레드 문제 발생 여지가 있으므로 사용주의)            
            Environment.Exit(0);
        }

        // 폴더명 가져오기  
        public string Get_Folder(string path)
        {            
            try
            {
                string[] foldernames = path.Split('\\');
                if (foldernames.Length != 0)
                {
                    return foldernames[foldernames.Length - 1];
                }
                else
                    return "";
            }
            catch 
            {   
                return null;
            }
        }

        // 폴더 복사 및 로그 생성
        public void Copy_Folder(string sourcePath, string targetPath)
        {
            // 소스 폴더 -> DB폴더의 파일을 모두 가져옴
            string[] files = System.IO.Directory.GetFiles(sourcePath);

            // 타겟 폴더 -> DB폴더로 파일을 하나씩 복사
            foreach (string file in files)
            {
                // 타켓 폴더가 없으면 폴더 생성
                if (!System.IO.Directory.Exists(targetPath))                
                    System.IO.Directory.CreateDirectory(targetPath);                

                string fileName = System.IO.Path.GetFileName(file);
                string destfile = System.IO.Path.Combine(targetPath, fileName);
                
                System.IO.File.Copy(file, destfile, true);

                if (fileName == "FPER.FDB")
                {
                    txt += string.Format("FDB Upate : {0} -> {1}\r\n",
                        File.GetCreationTime(file),
                        File.GetCreationTime(destfile)
                        );
                }
                else if (fileName == "CommDaemon.exe")
                {
                    txt += string.Format("CommDaemon Upate : {0} -> {1}\r\n",
                        FileVersionInfo.GetVersionInfo(file).FileVersion,
                        FileVersionInfo.GetVersionInfo(destfile).FileVersion
                        );
                }
                else if (fileName == "FPER.exe")
                {
                    txt += string.Format("FPER Upate : {0} -> {1}\r\n",
                        FileVersionInfo.GetVersionInfo(file).FileVersion,
                        FileVersionInfo.GetVersionInfo(destfile).FileVersion
                        );
                }
                else if (fileName == "FLauncher.exe")
                {
                    txt += string.Format("FLauncher Upate : {0} -> {1}\r\n",
                        FileVersionInfo.GetVersionInfo(file).FileVersion,
                        FileVersionInfo.GetVersionInfo(destfile).FileVersion
                        );
                }
                txt += string.Format("File Upate : {0}\r\n", destfile);

            }
        }
    }
}