using CrxSampleAddinSetting;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Windows.Forms;

namespace SetupConfiguration
{
    public class WindowWrapper : IWin32Window
    {
        private readonly IntPtr hwnd;
        public IntPtr Handle
        {
            get { return hwnd; }
        }
        public WindowWrapper(IntPtr handle)
        {
            hwnd = handle;
        }
    }
    public static class TopMostMessageBox
    {
        public static void Show(string message)
        {
            var proc = Process.GetProcessesByName("msiexec").FirstOrDefault(p => p.MainWindowTitle == "IroncadCrxSampleCs");
            if (proc != null)
            {
                MessageBox.Show(new WindowWrapper(proc.MainWindowHandle), message); // 結果、メッセージボックスも最前面に表示される
            }
            else
            {
                MessageBox.Show(message); // 結果、メッセージボックスも最前面に表示される
            }
        }
    }
    
    [System.ComponentModel.RunInstaller(true)]
    public class IronCAD_Config : System.Configuration.Install.Installer
    {
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);
#if false
            MessageBox.Show("install", "debug", MessageBoxButtons.OK);
#endif
            string targetdir = this.Context.Parameters["dir"];
            targetdir = targetdir.TrimEnd('\\');
            string crxFilePath = Path.Combine(targetdir, "IroncadCrxSampleCs.crx");
           
            /* IRONCAD[CAXA]のConfigファイルを書き換える */
            bool ret1 = AddinConfig.AddConfig(@"C:\Program Files\IronCAD\2022\bin\CAXADraft\Modules\CxAutorun.cx",
                                    crxFilePath);
            bool ret2 = AddinConfig.AddConfig(@"C:\Program Files\IronCAD\2023\bin\CAXADraft\Modules\CxAutorun.cx",
                                    crxFilePath);
            bool ret3 = AddinConfig.AddConfig(@"C:\Program Files\IronCAD\2024\bin\CAXADraft\Modules\CxAutorun.cx",
                                    crxFilePath);
            bool ret4 = AddinConfig.AddConfig(@"C:\Program Files\IronCAD\2025\bin\CAXADraft\Modules\CxAutorun.cx",
                                    crxFilePath);
            if ((ret1 != true) && (ret2 != true) && (ret3 != true) && (ret4 != true))
            {
                TopMostMessageBox.Show("IRONCADが見つかりませんでした。\n(インストールは続行されます)");
            }

        }

        public override void Commit(System.Collections.IDictionary savedState)
        {
            base.Commit(savedState);
        }

        public override void Rollback(System.Collections.IDictionary savedState)
        {
            base.Rollback(savedState);
        }

        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            base.Uninstall(savedState);
#if false
            MessageBox.Show("uninstall", "debug", MessageBoxButtons.OK);
#endif
            string targetdir = this.Context.Parameters["dir"];
            targetdir = targetdir.TrimEnd('\\');
            string crxFilePath = Path.Combine(targetdir, "IroncadCrxSampleCs.crx");

            for (int count = 0; count < 10; count++)
            {
                int delnum =  AddinConfig.DeleteConfig(@"C:\Program Files\IronCAD\2022\bin\CAXADraft\Modules\CxAutorun.cx",
                                                           crxFilePath);
                delnum += AddinConfig.DeleteConfig(@"C:\Program Files\IronCAD\2023\bin\CAXADraft\Modules\CxAutorun.cx",
                                           crxFilePath);
                delnum += AddinConfig.DeleteConfig(@"C:\Program Files\IronCAD\2024\bin\CAXADraft\Modules\CxAutorun.cx",
                                           crxFilePath);
                delnum += AddinConfig.DeleteConfig(@"C:\Program Files\IronCAD\2025\bin\CAXADraft\Modules\CxAutorun.cx",
                                           crxFilePath);
                if (delnum == 0)
                {
                    break;
                }
            }
            //UnRegistCOM();
            //CheckAndDeleteTransferClient();
        }


        /// <summary>
        /// ファイルにEveryOneのアクセス権限を付与する
        /// </summary>
        /// <param name="filePath"></param>
        private void setEveryOneAccessControl(string filePath)
        {
            if(File.Exists(filePath) != true)
            {
                return;
            }
            /* EveryOneのアクセス権限を作成する */
            FileSystemAccessRule rule = new FileSystemAccessRule(
              new NTAccount("everyone"),
              FileSystemRights.Modify,
              AccessControlType.Allow);

            /* 現在のアクセス権限を取得する */
            FileSecurity security = File.GetAccessControl(filePath);

            /* EveryOne権限を追加する */
            security.AddAccessRule(rule);
            File.SetAccessControl(filePath, security);
        }
    }
}
