//******************************************************************************//
// LogDashboardCtrl.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 Raytheon.LogDashboard.ViewModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Deployment.Application;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace Raytheon.LogDashboard.View
{
	/// <summary>
	/// Interaction logic for LogDashboardCtrl.xaml
	/// </summary>
	public partial class LogDashboardCtrl
	{
		public static IntPtr WindowHandle { get; private set; }

		public LogDashboardCtrl()
		{
			InitializeComponent();

			AutoScrollButton.ToolTip = "Enable Auto Scroll";
		}

		private void MetroContentControl_Loaded(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")))
				{
					((LogDashboardViewModel)DataContext).ImportLogs(arg);
				}
				return;
			}

            List<string> args = Environment.GetCommandLineArgs().Where(x => x.EndsWith(".txt") || x.EndsWith(".log")).ToList();

			if (args.Any())
			{
				((LogDashboardViewModel)DataContext).ImportLogs(args.Where(x => x.EndsWith(".txt") || x.EndsWith(".log")));
				return;
			}

			DisplayChangeLog();

		}

		private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
            if(AutoScrollEnabled && LogsListView.Items.Count > 0)
            {
                AutoScrollEnabled = false;
            }

            Task.Run(() =>
			{
				Application.Current.Dispatcher.Invoke(() =>
				{
					LogsListView.ScrollIntoView(LogsListView.SelectedItem);
					//TODO
					//LoggersTreeView.BringIntoView();
				});
			});
		}

		#region Logging scroll

		private bool autoScrollEnabled = true;
		protected bool AutoScrollEnabled
		{
			get => autoScrollEnabled;
			set
			{
				autoScrollEnabled = value;
				if (autoScrollEnabled)
				{
					AutoScrollButton.Opacity = 0.5;
					AutoScrollButton.ToolTip = "Disable Auto Scroll";
				}
				else
				{
					AutoScrollButton.ToolTip = "Enable Auto Scroll";
					AutoScrollButton.Opacity = 1;
				}
			}
		}

		private void OnScrollToTopButtonClick(object sender, RoutedEventArgs e)
		{
			if (LogsListView.Items.Count > 0)
            {
                LogsListView.ScrollIntoView(LogsListView.Items[0]);
            }
        }

		private void OnAutoScrollToBottomButtonClick(object sender, RoutedEventArgs e)
		{
			if (AutoScrollEnabled)
            {
                AutoScrollEnabled = false;
            }
            else
			{
				if (LogsListView.Items.Count > 0)
                {
                    LogsListView.ScrollIntoView(LogsListView.Items[LogsListView.Items.Count - 1]);
                }

                AutoScrollEnabled = true;
			}
		}

		private void OnScrollToBottomButtonClick(object sender, RoutedEventArgs e)
		{
			if (LogsListView.Items.Count > 0)
            {
                LogsListView.ScrollIntoView(LogsListView.Items[LogsListView.Items.Count - 1]);
            }
        }

		private void LogsListView_OnScrollChanged(object sender, ScrollChangedEventArgs e)
		{
			if (AutoScrollEnabled && LogsListView.Items.Count > 0 && e.VerticalChange < 0)
            {
                AutoScrollEnabled = false;
            }

            if (AutoScrollEnabled && LogsListView.Items.Count > 0)
            {
                LogsListView.ScrollIntoView(LogsListView.Items[LogsListView.Items.Count - 1]);
            }
        }

		#endregion

		#region table sorting

		GridViewColumnHeader lastHeaderClicked = null;
		ListSortDirection lastDirection = ListSortDirection.Ascending;

		private void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
		{
            GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;

			if (headerClicked != null && (string)headerClicked.Content == "Message")
            {
                return;
            }

            if (headerClicked != null)
			{
				if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
				{
					ListSortDirection direction;
					if (headerClicked != lastHeaderClicked)
					{
						direction = ListSortDirection.Ascending;
					}
					else
					{
						direction = lastDirection == ListSortDirection.Ascending
							? ListSortDirection.Descending
							: ListSortDirection.Ascending;
					}

                    Binding columnBinding = headerClicked.Column.DisplayMemberBinding as Binding;
                    string sortBy = columnBinding?.Path.Path ?? headerClicked.Column.Header as string;

					Sort(sortBy, direction);

					if (direction == ListSortDirection.Ascending)
					{
						headerClicked.Column.HeaderTemplate = Resources["HeaderTemplateArrowUp"] as DataTemplate;
					}
					else
					{
						headerClicked.Column.HeaderTemplate = Resources["HeaderTemplateArrowDown"] as DataTemplate;
					}

					// Remove arrow from previously sorted header  
					if (lastHeaderClicked != null && lastHeaderClicked != headerClicked)
					{
						lastHeaderClicked.Column.HeaderTemplate = null;
					}

					lastHeaderClicked = headerClicked;
					lastDirection = direction;
				}
			}
		}

		private void Sort(string sortBy, ListSortDirection direction)
		{
			ICollectionView dataView = CollectionViewSource.GetDefaultView(LogsListView.ItemsSource);

			dataView.SortDescriptions.Clear();
			SortDescription sd = new SortDescription(sortBy, direction);
			dataView.SortDescriptions.Add(sd);
			dataView.Refresh();
		}

		#endregion

		#region Drag and Drop

		private void LogsListView_OnDragOver(object sender, DragEventArgs e)
		{
            string file = ((string[])e.Data.GetData(DataFormats.FileDrop))?.FirstOrDefault(
				x => Path.GetExtension(x) == ".txt" ||
					 Path.GetExtension(x) == ".log" ||
                     Path.GetExtension(x) == ".csv");

			e.Effects = file != null ? DragDropEffects.Copy : DragDropEffects.None;
			e.Handled = true;
		}

		private void LogsListView_OnDrop(object sender, DragEventArgs e)
		{
			e.Effects = DragDropEffects.Copy;
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
			{
				string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
				if (files != null && files.Any())
				{
					var logFiles = files.Where(x => Path.GetExtension(x) == ".txt" ||
												    Path.GetExtension(x) == ".log" || 
                                                    Path.GetExtension(x) == ".csv");
					if (logFiles.Any())
					{
						((LogDashboardViewModel)DataContext).ImportLogs(logFiles);
					}
				}
			}
		}

		#endregion

		private void DisplayChangeLog()
		{
			if (!ApplicationDeployment.IsNetworkDeployed || !ApplicationDeployment.CurrentDeployment.IsFirstRun)
            {
                return;
            }

            ReleaseNotesDialog releaseNotesDialog = new ReleaseNotesDialog
            {
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };
            releaseNotesDialog.ShowDialog();
		}
    }
}
