//******************************************************************************//
// MainWindow.xaml.cs
// 12/4/2023
//
// RAYTHEON PROPRIETARY: THIS DOCUMENT CONTAINS DATA OR INFORMATION
// PROPRIETARY TO RAYTHEON COMPANY AND IS RESTRICTED TO USE ONLY BY PERSONS
// AUTHORIZED BY RAYTHEON COMPANY IN WRITING TO USE IT. DISCLOSURE TO
// UNAUTHORIZED PERSONS WOULD LIKELY CAUSE SUBSTANTIAL COMPETITIVE HARM TO
// RAYTHEON COMPANY'S BUSINESS POSITION. NEITHER SAID DOCUMENT NOR ITS
// CONTENTS SHALL BE FURNISHED OR DISCLOSED TO OR COPIED OR USED BY PERSONS
// OUTSIDE RAYTHEON COMPANY WITHOUT THE EXPRESS WRITTEN APPROVAL OF RAYTHEON
// COMPANY.
//
// THIS PROPRIETARY NOTICE IS NOT APPLICABLE IF DELIVERED TO THE U.S. GOVERNMENT
//
// UNPUBLISHED WORK - COPYRIGHT RAYTHEON COMPANY.
//
// WARNING: THIS DOCUMENT CONTAINS TECHNICAL DATA AND / OR TECHNOLOGY WHOSE
// EXPORT OR DISCLOSURE TO NON-U.S. PERSONS, WHEREVER LOCATED, IS RESTRICTED
// BY THE INTERNATIONAL TRAFFIC IN ARMS REGULATIONS (ITAR) (22 C.F.R. SECTION
// 120-130) OR THE EXPORT ADMINISTRATION REGULATIONS (EAR) (15 C.F.R. SECTION
// 730-774). THIS DOCUMENT CANNOT BE EXPORTED (E.G., PROVIDED TO A SUPPLIER
// OUTSIDE OF THE UNITED STATES) OR DISCLOSED TO A NON-U.S. PERSON, WHEREVER
// LOCATED, UNTIL A FINAL JURISDICTION AND CLASSIFICATION DETERMINATION HAS
// BEEN COMPLETED AND APPROVED BY RAYTHEON, AND ANY REQUIRED U.S. GOVERNMENT
// APPROVALS HAVE BEEN OBTAINED. VIOLATIONS ARE SUBJECT TO SEVERE CRIMINAL
// PENALTIES.
//
// DOD 5220.22-M, INDUSTRIAL SECURITY MANUAL, CHAPTER 5, SECTION 1 THROUGH 9 :
// FOR CLASSIFIED DOCUMENTS FOLLOW THE PROCEDURES IN OR DOD 5200.1-R,
// INFORMATION SECURITY PROGRAM, CHAPTER 6. FOR UNCLASSIFIED, LIMITED DOCUMENTS
// DESTROY BY ANY  METHOD THAT WILL PREVENT DISCLOSURE OF CONTENTS OR
// RECONSTRUCTION OF THE DOCUMENT.
// POC: Alex Kravchenko (1118268)
//******************************************************************************//
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Forms;
using NLog;
using Raytheon.LogDashboard.Helpers;
using Raytheon.LogDashboard.ViewModel;
using Application = System.Windows.Application;
using Raytheon.LogDashboard.Resources;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using GalaSoft.MvvmLight.Messaging;
using System.Collections.Generic;

namespace Raytheon.LogDashboard.View
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : MetroWindow, IDisposable
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();
        private NotifyIcon trayIcon;

        public MainWindow()
        {
            InitializeComponent();

            Loaded += (s, e) =>
            {
                WindowHandle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
                HwndSource.FromHwnd(WindowHandle)?.AddHook(HandleMessages);
			};
        }

        /// <summary>
        /// On Loaded Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments?.ActivationData != null)
            {
                string[] activationData = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData;
                foreach (var arg in activationData.Where(x => x.EndsWith(".txt") || x.EndsWith(".log") || x.EndsWith(".csv")))
                {
                    ViewModelLocator.LogDashboard.ImportLogs(arg);
                }
                return;
            }

            List<string> args = Environment.GetCommandLineArgs().Where(x => x.EndsWith(".txt") || x.EndsWith(".log") || x.EndsWith(".csv")).ToList();
            if (args.Any())
            {
                ViewModelLocator.LogDashboard.ImportLogs(args.Where(x => x.EndsWith(".txt") || x.EndsWith(".log") || x.EndsWith(".csv")));
                return;
            }
        }

		#region tray

		protected override void OnStateChanged(EventArgs e)
		{
			if (WindowState == WindowState.Minimized && Model.Settings.Instance.MinimizeToTray)
			{
				if (trayIcon == null)
				{
					trayIcon = new NotifyIcon
					{
						Icon = Resource1.LogDashboard,
						Visible = true,
						Text = "Log Viewer"
					};
					trayIcon.DoubleClick += delegate
					{
						Show();
						WindowState = WindowState.Normal;
					};

					trayIcon.ContextMenuStrip = new ContextMenuStrip();
					ToolStripMenuItem openAppMenuItem = new ToolStripMenuItem("Open");
					ToolStripMenuItem exitAppMenuItem = new ToolStripMenuItem("Exit");

					trayIcon.ContextMenuStrip.Items.AddRange(new ToolStripItem[] { openAppMenuItem, exitAppMenuItem });
					trayIcon.ContextMenuStrip.ItemClicked += TrayIconContextMenuClick;
				}
				Hide();
			}

			base.OnStateChanged(e);
		}

		private void TrayIconContextMenuClick(object sender, ToolStripItemClickedEventArgs e)
		{
			switch (e.ClickedItem.Text)
			{
				case "Open":
					Show();
					WindowState = WindowState.Normal;
					break;
				case "Exit":
					Close();
					Environment.Exit(0);
					break;
			}
		}

		protected override void OnClosed(EventArgs e)
		{
			if (trayIcon != null)
			{
				trayIcon.Visible = false;
				trayIcon.Dispose();
				trayIcon.Icon = null;
			}

			base.OnClosed(e);
		}

		#endregion


		#region param transfer

		public static IntPtr WindowHandle { get; private set; }

        internal static void HandleParameter(string[] args)
        {
            if (Application.Current?.MainWindow is MainWindow mainWindow &&
                args != null && args.Length > 0 && args.All(x => x.EndsWith(".txt") || x.EndsWith(".log") || x.EndsWith(".csv")))
            {
                ViewModelLocator.LogDashboard.ImportLogs(args.First());
            }
        }

        private static IntPtr HandleMessages(IntPtr handle, int message, IntPtr wParameter, IntPtr lParameter, ref Boolean handled)
        {
            string data = UnsafeNative.GetMessage(message, lParameter);

            if (data != null)
            {
                if(Application.Current.MainWindow == null)
                {
                    return IntPtr.Zero;
                }

                if(Application.Current.MainWindow.WindowState == WindowState.Minimized)
                {
                    Application.Current.MainWindow.WindowState = WindowState.Normal;
                }

                UnsafeNative.SetForegroundWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle);

                string[] args = data.Split(' ');
                HandleParameter(args);
                handled = true;
            }

            return IntPtr.Zero;
        }

        #endregion

        public void Dispose()
        {
            trayIcon?.Dispose();
        }

		private void MetroWindow_Closing(object sender, CancelEventArgs e)
		{
            ViewModelLocator.LogDashboard.Dispose();
        }
	}
}