using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using IWshRuntimeLibrary;

namespace NewPosInstaller
{
    public class PosInstallComplete : Echo, IProcess
    {
        //private bool isStop = false; 

        public bool Execute()
        {
            try
            {
                bool retValue = false;

                retValue = CreateShortcut();
                retValue = InstallFonts();

                return retValue;
            }
            catch (Exception ex)
            {
                ComLog.WriteLog(ComLog.Level.Exception
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , ex.Message);
                return false;
            }
        }

        public void Stop()
        {
            //isStop = true;
        }

        private bool CreateShortcut()
        {
            var retValue = false;
            try
            {
                base.OnEcho("Create Shortcut.");

                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , "Start");

                var iconFile = string.Empty;
                var fileName = string.Empty;
                if (BasicInfo.CompCd.StartsWith("PC") && BasicInfo.BrandCd == "002")
                {
                    // PB: 파리바케뜨
                    //iconFile = @"window_icon_pb_icon.ico"; 
                    iconFile = @"PB.ico"; 
                    fileName = "PB POS " + BasicInfo.StoreNm;
                }
                if (BasicInfo.CompCd.StartsWith("PC") && BasicInfo.BrandCd == "005")
                {
                    // PS: 파스쿠치
                    iconFile = @"PS.ico";
                    fileName = "PS POS " + BasicInfo.StoreNm;
                }  
                else if (BasicInfo.CompCd.StartsWith("BR") && BasicInfo.BrandCd == "3000")
                {
                    // BR:베스킨
                    iconFile = @"BR.ico";
                    fileName = "BR POS " + BasicInfo.StoreNm;
                }
                else if (BasicInfo.CompCd.StartsWith("BR") && BasicInfo.BrandCd == "5000")
                {
                    // DD:던킨
                    iconFile = @"DD.ico";
                    fileName = "DD POS " + BasicInfo.StoreNm;
                }
                else if (BasicInfo.CompCd.StartsWith(" SL"))
                {
                    // 삼립
                    iconFile = @"SL.ico";
                    fileName = "SPC POS " + BasicInfo.StoreNm;
                }
                else
                {
                    // 기타등등
                    iconFile = @"window_icon_spc_icon.ico"; 
                    fileName = "SPC POS " + BasicInfo.StoreNm;
                }

                var iconPath = Path.Combine(DirInfo.InstallDir, @"IMAGE\Icon\", iconFile);
                var startPath = Path.Combine(DirInfo.InstallDir, @"BIN");
                var targetPath = Path.Combine(startPath, "PosStart.exe");
                var shotcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), fileName + ".lnk");

                if (System.IO.File.Exists(iconPath) == false)
                {
                    iconFile = @"window_icon_spc_icon.ico";
                    iconPath = Path.Combine(DirInfo.InstallDir, @"IMAGE\Icon\", iconFile);
                }

                //// 그냥 계속 업데이트 해도 별로 상관없는것 같다. 
                //if (System.IO.File.Exists(shotcutPath))
                //{
                //    ComLog.WriteLog(ComLog.Level.trace
                //                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                //                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                //                  , string.Format("  => New POS Shortcut file already exists. file={0}", shotcutPath), true);
                //    return retValue = true; 
                //}

                WshShell wsh = new WshShell();
                IWshRuntimeLibrary.IWshShortcut shotCut = (IWshRuntimeLibrary.IWshShortcut)wsh.CreateShortcut(shotcutPath);
                shotCut.WorkingDirectory = startPath; 
                shotCut.TargetPath = targetPath;
                shotCut.Description = fileName;

                if (System.IO.File.Exists(iconPath))
                    shotCut.IconLocation = iconPath;

                shotCut.Save();

                Thread.Sleep(1000);
                retValue = System.IO.File.Exists(shotcutPath);

                return retValue = true;
            }
            catch (Exception ex)
            {
                ComLog.WriteLog(ComLog.Level.Exception
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , ex.Message);
                return retValue = false;
            }
            finally
            {
                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , string.Format("End, Result={0}", retValue ? "Success" : "Failed"));

                ComLog.SendLog(ComLog.Level.trace, string.Format("Create Shortcut, Result={0}", retValue ? "Success" : "Failed"));

            }
        }

        private bool InstallFonts()
        {
            bool retValue = false;
            try
            {
                base.OnEcho("Install Fonts");

                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , "Start");

                // Set ClearType
                Registry.SetValue(Microsoft.Win32.Registry.CurrentUser, @"Control Panel\Desktop", "FontSmoothing", "2");
                Registry.SetValue(Microsoft.Win32.Registry.CurrentUser, @"Control Panel\Desktop", "FontSmoothingType", 2);

                // 설치할 폰트 목록 정의  
                List<string[]> fontList = new List<string[]>();
                fontList.Add(new string[] { "KOR", "NanumGothic.ttf", "나눔고딕 (TrueType)" });
                fontList.Add(new string[] { "KOR", "NanumGothicBold.ttf", "나눔고딕 Bold (TrueType)" });
                fontList.Add(new string[] { "KOR", "NanumSquareR.ttf", "나눔스퀘어 (TrueType)" });
                fontList.Add(new string[] { "KOR", "NanumSquareB.ttf", "나눔스퀘어 Bold (TrueType)" });
                //fontList.Add(new string[] { "KOR", "malgun.ttf", "Malgun Gothic (TrueType)" });                       // => 맑은 고딕 폰트는 XP, Win7 별도설치 
                //fontList.Add(new string[] { "KOR", "malgunbd.ttf", "Malgun Gothic Bold (TrueType)" });
                foreach (string[] fontinfo in fontList)
                {
                    if (fontinfo[0] == "ALL" || fontinfo[0].ToUpper() == BasicInfo.Nation.ToUpper())
                    {
                        var fontFile = fontinfo[1];
                        var fontName = fontinfo[2];
                        RegistryFonsts(fontFile, fontName, false);
                    }
                }

                // 맑은 고딕
                if (Environment.OSVersion.Version.Major == 5)
                {
                    // Windows XP
                    //retValue = Install_VistaFont_KOR();
                    fontList.Clear();
                    fontList.Add(new string[] { "KOR", "malgun.ttf", "맑은 고딕 (TrueType)" });
                    fontList.Add(new string[] { "KOR", "malgunbd.ttf", "맑은 고딕 Bold(TrueType)" });
                    foreach(string[] fontinfo in fontList)
                    {
                        if (fontinfo[0] == "ALL" || fontinfo[0].ToUpper() == BasicInfo.Nation.ToUpper())
                        {
                            var fontFile = fontinfo[1];
                            var fontName = fontinfo[2];
                            RegistryFonsts(fontFile, fontName, true);
                        }
                    }
                }
                else
                {
                    // Windows 7
                    fontList.Clear();
                    fontList.Add(new string[] { "KOR", "malgun.ttf", "Malgun Gothic (TrueType)" });
                    fontList.Add(new string[] { "KOR", "malgunbd.ttf", "Malgun Gothic Bold (TrueType)" });
                    foreach (string[] fontinfo in fontList)
                    {
                        if (fontinfo[0] == "ALL" || fontinfo[0].ToUpper() == BasicInfo.Nation.ToUpper())
                        {
                            var fontFile = fontinfo[1];
                            var fontName = fontinfo[2];
                            RegistryFonsts(fontFile, fontName, false);
                        }
                    }
                }

                return retValue = true; ;
            }
            catch (Exception ex)
            {
                ComLog.WriteLog(ComLog.Level.Exception
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , ex.Message);
                return retValue = false;
            }
            finally
            {
                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , string.Format("End, Result={0}", retValue ? "Success" : "Failed"));
            }
        }

        /// <summary>
        /// 맑은고딕 폰트 설치 
        /// </summary>
        /// <returns></returns>
        private bool Install_VistaFont_KOR()
        {
            var retValue = false;
            try
            {
                //if (BasicInfo.Nation.ToUpper().Equals("KOR") == false) return true;
                //if (Environment.OSVersion.Version.Major != 5) return true;

                // Windows XP
                base.OnEcho("Install Fonts (Windows XP) => VistaFont_KOR");

                var sourDir = Path.Combine(DirInfo.InstallDir, @"TEMP");
                var fontDir = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
                var targPath = Path.Combine(fontDir, "malgun.ttf");
                if (System.IO.File.Exists(targPath))
                {
                    ComLog.WriteLog(ComLog.Level.trace
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , string.Format("  => Font already exists. file={0}", targPath));
                    return retValue = true;
                }
                System.IO.File.Move(Path.Combine(sourDir, "VistaFont_KOR.EXE_"), Path.Combine(sourDir, "VistaFont_KOR.EXE"));
                var procName = Path.Combine(sourDir, "VistaFont_KOR.EXE");
                var procArgs = @"/Q";
                if (System.IO.File.Exists(procName) == false)
                {
                    ComLog.WriteLog(ComLog.Level.Error
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , string.Format("  => File not found, file={0}", procName), true);
                    return retValue = false;
                }

                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , string.Format("  => Excute:{0}", procName));

                // 대기시간 5분
                ComLib.ExecuteWaitProcess(procName, procArgs, System.Diagnostics.ProcessWindowStyle.Hidden, 60000 * 5);

                Thread.Sleep(500);
                retValue = System.IO.File.Exists(Path.Combine(fontDir, "malgun.ttf"));

                System.IO.File.Move(Path.Combine(sourDir, "VistaFont_KOR.EXE"), Path.Combine(sourDir, "VistaFont_KOR.EXE_"));

                return retValue;
            }
            catch (Exception ex)
            {
                ComLog.WriteLog(ComLog.Level.Exception
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , ex.Message);
                return retValue = false;
            }
        }


        private bool RegistryFonsts(string fontFile, string fontName, bool bIsXP = false)
        {
            //var retValue = false;
            var ret = false;

            try
            {
                if (bIsXP == false)
                {
                    var sourDir = Path.Combine(DirInfo.InstallDir, @"TEMP");
                    var fontDir = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
                    var subKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts";

                    var sourPath = Path.Combine(sourDir, fontFile);
                    var targPath = Path.Combine(fontDir, fontFile);

                    base.OnEcho(string.Format("Install Fonts {0} {1}", fontName, fontFile));
                    ComLog.WriteLog(ComLog.Level.trace
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , string.Format("  => Install Fonts {0} {1}", fontName, fontFile));

                    if (System.IO.File.Exists(targPath))
                    {
                        ComLog.WriteLog(ComLog.Level.trace
                                      , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                      + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                      , string.Format("  => Font already exists. file={0}", targPath));
                        return true;
                    }
                    if (System.IO.File.Exists(sourPath) == false)
                    {
                        ComLog.WriteLog(ComLog.Level.Error
                                      , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                      + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                      , string.Format("  => File not found, file={0}", sourPath), true);
                        return false; ;
                    }

                    System.IO.File.Copy(sourPath, targPath, true);
                    Thread.Sleep(300);
                    ret = System.IO.File.Exists(targPath);
                    ComLog.WriteLog(ComLog.Level.trace
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , string.Format("  => Font file copy Resutl={0} FontName={1}", ret ? "Success" : "Failed", fontName), true);
                    if (ret == false) return false;

                    ret = Registry.SetValue(Microsoft.Win32.Registry.LocalMachine, subKey, fontName, fontFile);
                    ComLog.WriteLog(ComLog.Level.trace
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , string.Format("  => Registry font key Resutl={0} FontName={1}", ret ? "Success" : "Failed", fontName), true);
                }
                else
                {
                    var sourDir = Path.Combine(DirInfo.InstallDir, @"TEMP\XP");
                    var fontDir = Environment.GetFolderPath(Environment.SpecialFolder.Fonts);
                    var subKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts";

                    var sourPath = Path.Combine(sourDir, fontFile);
                    var targPath = Path.Combine(fontDir, fontFile);

                    base.OnEcho(string.Format("Install Fonts {0} {1}", fontName, fontFile));
                    ComLog.WriteLog(ComLog.Level.trace
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , string.Format("  => Install Fonts {0} {1}", fontName, fontFile));

                    if (System.IO.File.Exists(targPath))
                    {
                        ComLog.WriteLog(ComLog.Level.trace
                                      , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                      + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                      , string.Format("  => Font already exists. file={0}", targPath));
                        return true;
                    }
                    if (System.IO.File.Exists(sourPath) == false)
                    {
                        ComLog.WriteLog(ComLog.Level.Error
                                      , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                      + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                      , string.Format("  => File not found, file={0}", sourPath), true);
                        return false; ;
                    }

                    System.IO.File.Copy(sourPath, targPath, true);
                    Thread.Sleep(300);
                    ret = System.IO.File.Exists(targPath);
                    ComLog.WriteLog(ComLog.Level.trace
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , string.Format("  => Font file copy Resutl={0} FontName={1}", ret ? "Success" : "Failed", fontName), true);
                    if (ret == false) return false;

                    ret = Registry.SetValue(Microsoft.Win32.Registry.LocalMachine, subKey, fontName, fontFile);
                    ComLog.WriteLog(ComLog.Level.trace
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , string.Format("  => Registry font key Resutl={0} FontName={1}", ret ? "Success" : "Failed", fontName), true);
                }
                if (ret == false) return false;

                return true;
            }
            catch (Exception ex)
            {
                ComLog.WriteLog(ComLog.Level.Exception
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , ex.Message);
                return false;
            }
        }
    }
}
