using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using InABox.Core;
using InABox.WPF;
using Microsoft.Win32;

namespace InABox.DynamicGrid
{
    /// <summary>
    ///     Interaction logic for KanbanAttachments.xaml
    /// </summary>
    public partial class Attachments : UserControl
    {
        private readonly List<Tuple<string, BitmapImage, byte[], int>> Items = new();

        private readonly List<string> ViewedFiles = new();

        public Attachments(Type type, Guid reference)
        {
            InitializeComponent();
            FileList.Items.Clear();
            FileList.ItemsSource = Items;
            //for (int i = 0; i < files.Count(); i++)
            //{
            //    var file = files[i];
            //    Items.Add(new Tuple<string, BitmapImage, byte[], int>(file.FileName, GetBitmapImage(file.FileName), file.Data, i));
            //}
        }

        private BitmapImage GetBitmapImage(string filename)
        {
            var bmp = Wpf.Resources.doc_misc;
            var ext = Path.GetExtension(filename).ToUpper();
            if (ext.Equals(".PDF"))
                bmp = Wpf.Resources.doc_pdf;
            else if (ext.Equals(".DOC") || ext.Equals(".DOCX") || ext.Equals(".RTF"))
                bmp = Wpf.Resources.doc_rtf;
            else if (ext.Equals(".XLS") || ext.Equals(".XLSX"))
                bmp = Wpf.Resources.doc_xls;
            else if (ext.Equals(".TXT"))
                bmp = Wpf.Resources.doc_txt;
            else if (ext.Equals(".BMP"))
                bmp = Wpf.Resources.doc_bmp;
            else if (ext.Equals(".PNG"))
                bmp = Wpf.Resources.doc_png;
            else if (ext.Equals(".JPG") || ext.Equals(".JPEG"))
                bmp = Wpf.Resources.doc_jpg;
            return bmp.AsBitmapImage().Resize(64, 64);
        }

        //      public void UnloadAttachments(List<MiscellaneousDataFile> files)
        //      {
        //	// First remove any deleted files
        //	for (int i = files.Count - 1; i >= 0; i--)
        //	{
        //		if (!Items.Where(x => x.Item4.Equals(i)).Any())
        //			files.RemoveAt(i);
        //	}
        //	// now add new files
        //	foreach (var item in Items)
        //	{
        //		if (item.Item4.Equals(-1))
        //			files.Add(new MiscellaneousDataFile() { FileName = item.Item1, Data = item.Item3 });
        //	}
        //}

        ~Attachments()
        {
            foreach (var file in ViewedFiles)
                if (File.Exists(file))
                    try
                    {
                        File.Delete(file);
                    }
                    catch (Exception e)
                    {
                        Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
                    }
        }

        private void AddFile_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new OpenFileDialog();
            dlg.Filter = ""; // new MiscellaneousDataFile().Filter();
            if (dlg.ShowDialog() == true)
            {
                var tuple = new Tuple<string, BitmapImage, byte[], int>(
                    Path.GetFileName(dlg.FileName),
                    GetBitmapImage(dlg.FileName),
                    File.ReadAllBytes(dlg.FileName),
                    -1
                );
                Items.Add(tuple);
                FileList.ItemsSource = null;
                FileList.ItemsSource = Items;
            }
        }

        private void ViewFile(object tag)
        {
            if (tag is Tuple<string, BitmapImage, byte[], int>)
            {
                var tuple = (Tuple<string, BitmapImage, byte[], int>)tag;
                var filename = Path.ChangeExtension(Path.GetTempFileName(), Path.GetExtension(tuple.Item1));
                File.WriteAllBytes(filename, tuple.Item3);
                ViewedFiles.Add(filename);
                var gsProcessInfo = new ProcessStartInfo();
                gsProcessInfo.Verb = "open";
                gsProcessInfo.WindowStyle = ProcessWindowStyle.Normal;
                gsProcessInfo.FileName = filename;
                gsProcessInfo.UseShellExecute = true;

                Process.Start(gsProcessInfo);
            }
        }

        private void ViewFile_Click(object sender, RoutedEventArgs e)
        {
            var tag = (sender as MenuItem).Tag;
            ViewFile(tag);
        }

        private void DeleteFile_Click(object sender, RoutedEventArgs e)
        {
            var tag = (sender as MenuItem).Tag;
            if (tag is Tuple<string, BitmapImage, byte[], int>)
            {
                var tuple = (Tuple<string, BitmapImage, byte[], int>)tag;
                if (MessageBox.Show("Are you sure you wish to delete this file?", "Confirm File Delete", MessageBoxButton.YesNo)
                    .Equals(MessageBoxResult.Yes))
                {
                    Items.Remove(tuple);
                    FileList.ItemsSource = null;
                    FileList.ItemsSource = Items;
                }
            }
        }

        private void Item_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left && e.ClickCount == 2)
            {
                var tag = (sender as FrameworkElement).Tag;
                ViewFile(tag);
            }
        }
    }
}