using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using System.Text;

using Microsoft.Win32;

using C4IT.Logging;

using FasdDesktopUi.Basics.Models;

using static C4IT.Logging.cLogManager;
using System.Reflection;
using System.Runtime.InteropServices;
using C4IT.MultiLanguage;

namespace FasdDesktopUi.Basics.UiActions
{
    abstract public class cUiCopyDetailsTableContentBase : cUiActionBase
    {
        private cDetailedDataModel Data;

        public cUiCopyDetailsTableContentBase(cDetailedDataModel Data)
        {
            this.Data = Data;
        }

        internal String getContentString(bool csv)
        {
            try
            {
                string retVal = String.Empty;
                char separator = csv ? ';' : '\t';

                if (!Data.HasColumnHeaders)
                    retVal = Data.Heading;

                foreach (var row in Data.FullDetailedData)
                {
                    if (!(row is List<object> _lst))
                        continue;

                    var line = String.Empty;
                    foreach (var cell in _lst)
                    {
                        if (!string.IsNullOrEmpty(line))
                            line += separator;

                        var item = cell.ToString();
                        if (csv && item.Contains(separator.ToString()))
                        {
                            item = item.Replace("\"", "\"\"");
                            item = "\"" + item + "\"";
                        }

                        line += item;
                    }
                    if (!string.IsNullOrEmpty(line))
                    {
                        if (!string.IsNullOrEmpty(retVal))
                            retVal += "\n";
                        retVal += line;
                    }
                }

                return retVal;
            }
            catch (Exception E)
            {
                LogException(E);
            }

            return null;
        }
    }

    public class cUiCopyDetailsTableContent : cUiCopyDetailsTableContentBase
    {
        public cUiCopyDetailsTableContent (cDetailedDataModel Data) : base(Data)
        {
        }

        public override async Task<bool> RunUiActionAsync(object sender, System.Windows.UIElement UiLocation, bool isDetailedLayout, cSupportCaseDataProvider dataProvider)
        {
            await Task.CompletedTask;

            var strCipboard = getContentString(false);
            if (string.IsNullOrEmpty(strCipboard))
                return true;

            strCipboard += "\n";
            System.Windows.Forms.Clipboard.SetText(strCipboard);

            return false;
        }
    }


    public class cUiSaveDetailsTableContent : cUiCopyDetailsTableContentBase
    {
        public cUiSaveDetailsTableContent(cDetailedDataModel Data) : base(Data)
        {
        }


        [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
        static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out string pszPath);

        public static readonly Guid DownloadsFolderID = new Guid("374DE290-123F-4565-9164-39C4925E467B");

        public static string GetSpecialWindowsFolder(Guid FolderID)
        {
            try
            {
                string _folder;
                if (SHGetKnownFolderPath(FolderID, 0, IntPtr.Zero, out _folder) == 0)
                    return _folder;

            }
            catch (Exception E)
            {
                LogException(E);
            }
            return String.Empty;
        }

        public override async Task<bool> RunUiActionAsync(object sender, System.Windows.UIElement UiLocation, bool isDetailedLayout, cSupportCaseDataProvider dataProvider)
        {

            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            try
            {
                await Task.CompletedTask;

                var strContent = getContentString(false);

                if (string.IsNullOrEmpty(strContent))
                    return true;

                var LastDirectory = cFasdCockpitConfig.Instance.LastDownloadPath;
                if (string.IsNullOrEmpty(LastDirectory))
                    LastDirectory = GetSpecialWindowsFolder(DownloadsFolderID);

                SaveFileDialog saveFileDialog = new SaveFileDialog()
                {
                    Filter = "Tab-separated file (*.txt)|*.txt|Comma-serarated file (*.csv)|*.csv",
                    Title = cMultiLanguageSupport.GetItem("DetailsPage.DetailTable.ContentDownload"),
                    InitialDirectory = LastDirectory
                };

                if (saveFileDialog.ShowDialog() != true)
                    return true;

                if (Path.GetExtension(saveFileDialog.FileName).ToLower() == ".csv")
                    strContent = getContentString(true);

                File.WriteAllText(saveFileDialog.FileName, strContent, Encoding.UTF8);

                cFasdCockpitConfig.Instance.LastDownloadPath = Path.GetDirectoryName(saveFileDialog.FileName);
                cFasdCockpitConfig.Instance.Save("LastDownloadPath");

                return true;
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
            }

            return false;
        }
    }

}
