using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mail;
using System.Text;
using Microsoft.Extensions.Configuration;

namespace Kit.Helpers.Log
{
    public enum LogMessageType
    {
        Debug = 1,
        Info,
        Warn,
        Error,
    }

    public static class Logger
    {
        private static string _pathLogFolder;
        private static string _emailas;
        private static bool _isSendEmail;
        public static void Configure(IConfiguration configuration)
        {
            var config = new ConfigurationHelper(configuration, "Log");
            _pathLogFolder = config.GetAppSettingValue("PathFolder");

            if (_pathLogFolder.IsNullOrEmpty() || Directory.Exists(_pathLogFolder) == false)
                _pathLogFolder = Path.GetTempPath();

            _isSendEmail = config.GetAppSettingValue("IsSendMail").TryParseToBool(false);
            _emailas = config.GetAppSettingValue("Emails");
        }

        public static string GetCurrentFullFileName()
        {
            var dt = DateTime.UtcNow;
            return Path.Combine(_pathLogFolder, String.Format("log_{0}_{1}_{2}.log", dt.Day, dt.Month, dt.Year));
        }

        public static string GetNameMessageType(LogMessageType type)
        {
            switch (type)
            {
                case LogMessageType.Debug:
                    return "Дебаг";
                case LogMessageType.Error:
                    return "Ошибка";
                case LogMessageType.Info:
                    return "Информация";
                case LogMessageType.Warn:
                    return "Предупреждение";
            }
            return String.Empty;
        }

        public static void Log(LogMessageType type, string log)
        {
            string path = GetCurrentFullFileName();
            using (var file = File.AppendText(path))
            {
                var str = String.Format("{0}:({1}) {2}" + Environment.NewLine, DateTime.UtcNow, GetNameMessageType(type), log);
                file.WriteLine(str);
                if (_isSendEmail && type == LogMessageType.Error)
                    SendMail(new StringBuilder(str));
            }
        }

        public static void Log(LogMessageType type, string log, params object[] args)
        {
            Log(type, String.Format(log, args));
        }

        public static void LogError(string header, string error)
        {
            using (var file = File.AppendText(GetCurrentFullFileName()))
            {
                file.WriteLine(String.Format("{0}:({1}) {2}", DateTime.UtcNow, GetNameMessageType(LogMessageType.Error), header));
                file.WriteLine(String.Format("Trace: {0}" + Environment.NewLine, error));
            }
        }


        public static void LogInfo(string log, params object[] args)
        {
            Log(LogMessageType.Info, String.Format(log, args));
        }

        public static void LogWarn(string log, params object[] args)
        {
            Log(LogMessageType.Warn, String.Format(log, args));
        }


        public static void SendMail(StringBuilder errorText)
        {
            List<MailMessage> gettersMailMessages = new List<MailMessage>();
            List<string> Getters = new List<string>();

            foreach (var mail in _emailas.Replace(",", ";").Split(';'))
            {
                Getters.Add(mail);
            }

            if (!string.IsNullOrEmpty(errorText.ToString()))
            {

                foreach (var getter in Getters)
                {
                    var mail = new MailMessage
                    {
                        From = new MailAddress("noreply@aetalon.ru", "Ошибка Эталон"),
                        Subject = "Ошибка Эталон",
                        IsBodyHtml = false,
                        Body = errorText.ToString()
                    };

                    mail.Body = mail.Body.Replace("_EMAIL_RECEIVER_", Base64Encode(errorText.ToString()));
                    mail.To.Add(getter);
                    gettersMailMessages.Add(mail);
                }
            }


            using (var smtp = new SmtpClient())
            {
                foreach (var mail in gettersMailMessages)
                {
                    try
                    {
                        smtp.Send(mail);
                    }
                    catch (Exception e)
                    {

                    }
                }

            }

        }

        public static string Base64Encode(string plainText)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }
    }
}