using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.Office.Tools;

namespace OutlookAIAssistant
{
    public partial class ThisAddIn
    {
        public CustomTaskPane AIAssistantTaskPane;
        private UI.TaskPaneHost taskPaneHost;
        private Process backendProcess;

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            // Initialize WPF Task Pane Host
            taskPaneHost = new UI.TaskPaneHost();
            AIAssistantTaskPane = this.CustomTaskPanes.Add(taskPaneHost, "AI Assistant");
            AIAssistantTaskPane.Width = 350;
            AIAssistantTaskPane.Visible = false;

            StartBackendService();
        }

        private void StartBackendService()
        {
            try
            {
                // Assuming BackendService.exe is installed in the same directory as the Add-in DLL
                string assemblyPath = Assembly.GetExecutingAssembly().Location;
                string installDir = Path.GetDirectoryName(assemblyPath);
                string backendExePath = Path.Combine(installDir, "BackendService.exe");

                if (File.Exists(backendExePath))
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo
                    {
                        FileName = backendExePath,
                        UseShellExecute = false,
                        CreateNoWindow = true, // Hide console window completely
                        WindowStyle = ProcessWindowStyle.Hidden
                    };

                    backendProcess = Process.Start(startInfo);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Failed to start backend service: " + ex.Message);
            }
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            // Note: Outlook no longer raises this event by default. 
            // However, if the process is attached, we can attempt to kill it.
            try
            {
                if (backendProcess != null && !backendProcess.HasExited)
                {
                    backendProcess.Kill();
                }
            }
            catch { }
        }

        protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
        {
            return new Ribbon();
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}
