using System.Linq;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.Win32;
using System.Diagnostics;
using Gremlin.GremlinUI.ViewModels;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace Gremlin.GremlinUtilities
{
    internal static class FileIO
    {
        public static string ReadResource(string name)
        //Source and credit to: https://stackoverflow.com/questions/3314140/how-to-read-embedded-resource-text-file  
        {
            Assembly assembly = Assembly.GetExecutingAssembly();

            // Format: "{Namespace}.{Folder}.{filename}.{Extension}"
            string resourcePath = name.StartsWith(nameof(Gremlin))
                ? name
                : assembly.GetManifestResourceNames().Single(str => str.EndsWith(name));

            using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
            using (StreamReader reader = new(stream))
            {
                return reader.ReadToEnd();
            }
        }

        private static readonly Encoding defaultEncodingIfNoBom = Encoding.UTF8;

        public static string GetFilepathFromUser(string filter = "Delimited Data File|*.csv; *.txt; *.tsv")
        {
            string _filepath = "";
            OpenFileDialog dlg = new()
            {
                Multiselect = false,
                Filter = filter
            };

            if (dlg.ShowDialog() == true)
            {
                //Auswahl dlg.filenames an passende Objekte übergeben
                _filepath = dlg.FileName;
            }
            return _filepath;
        }

        internal static void OpenFile(string path, string file, string type)
        {
            try
            {
                _ = Process.Start(path == "" ? $"{file}.{type}" : $"{path}\\{file}.{type}");
            }
            catch (Exception ex)
            {
                ErrorHandler.ShowErrorInMessageBox(ex);
            }
        }

        public static Encoding GetEncoding(string fileName)
        {
            Stream fileStream = File.OpenRead(fileName);
            using (StreamReader reader = new(fileStream, defaultEncodingIfNoBom, true))
            {
                _ = reader.Peek();
                Encoding encoding = reader.CurrentEncoding;
                return encoding;
            }
        }

        public static void SendQuoteViaMail(QuoteVM quoteVM)
        {
            Outlook.Application application = new();

            Outlook.MailItem mail = application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;

            mail.Subject = quoteVM.QuoteNumber;
            Outlook.AddressEntry currentUser = application.Session.CurrentUser.AddressEntry;
            
            if (currentUser.Type == "EX")
            {
                Outlook.ExchangeUser manager = currentUser.GetExchangeUser().GetExchangeUserManager();
                // Add recipient using display name, alias, or smtp address
                mail.Recipients.Add(manager.PrimarySmtpAddress);
                mail.Recipients.ResolveAll();
                mail.Attachments.Add($"{quoteVM.QuoteNumber}.pdf", Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                mail.Send();
            }
        }
    }
}