using System.ComponentModel;
using System.Net;
using System.Net.Mail;

public class MailToDoItem
{
    public int SeqNo { get; set; }
    // 服務名稱
    public string SourceId { get; set; }
    // 主要收信者(多個以;隔開)
    public string Mail_To { get; set; } = GlobalClass.appsettings("MailServer:smtp_username");
    // 副本收信者(多個以;隔開)
    public string Mail_Cc { get; set; } = "";
    // 信件主旨
    public string Subject { get; set; } = "";
    // 信件內容
    public string Message { get; set; } = "";
    // 寄信狀態(N, P, Y, F)
    // N: 尚未寄信
    // P: 寄信中
    // Y: 寄信完成
    // F: 寄信失敗(搭配ErrMessage)
    public string Status { get; set; } = "";
    // 寄信者
    public string SendUser { get; set; } = GlobalClass.appsettings("MailServer:smtp_username");
    // 寄信時間
    public DateTime? SendTime { get; set; } = DateTime.UtcNow;
    // 錯誤訊息
    public string ErrMessage { get; set; } = "";
}

public class MySmtpClient : IDisposable
{
    //private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
    private MailToDoItem _mailToDo;
    private SmtpClient _smtpClient;
    public event Action<MailToDoItem, AsyncCompletedEventArgs> MySendCompleted;
    public MySmtpClient(MailToDoItem mailToDo, EmailSetting emailSetting)
    {
        _mailToDo = mailToDo;

        _smtpClient = new SmtpClient(emailSetting.SmtpServer);
        _smtpClient.Port = emailSetting.SmtpPort;
        _smtpClient.Credentials = new NetworkCredential(emailSetting.Account, emailSetting.Password);
        _smtpClient.EnableSsl = true;
        _smtpClient.SendCompleted += new SendCompletedEventHandler(_smtpClient_SendCompleted);
    }

    private void _smtpClient_SendCompleted(object sender, AsyncCompletedEventArgs e)
    {
        //MySendCompleted(_mailToDo, e);
        //_smtpClient.SendCompleted -= _smtpClient_SendCompleted;
        this.Dispose();
    }

    public void SendMailProcess(string sysEmail
        , byte[] attach, string attachName)
    {
        MailMessage mailMessage = new MailMessage();

        var mailFrom = new MailAddress(sysEmail);
        mailMessage.From = mailFrom;
        foreach (var item in _mailToDo.Mail_To?.Split(","))
        {
            if (string.IsNullOrEmpty(item) == false)
                mailMessage.To.Add(item);
        }
        foreach (var item in _mailToDo.Mail_Cc?.Split(','))
        {
            if (string.IsNullOrEmpty(item) == false)
                mailMessage.CC.Add(item);
        }
        mailMessage.Body = _mailToDo.Message;
        mailMessage.Subject = _mailToDo.Subject;


        if (attach != null && attach?.Length > 0)
        {
            Attachment attachment = new Attachment(new MemoryStream(attach), attachName);
            mailMessage.Attachments.Add(attachment);
        }
        _smtpClient.SendMailAsync(mailMessage);
    }

    public void Dispose()
    {
        //_logger.Info($"[MySmtpClient Dispose]!!");
        this._smtpClient.Dispose();
        // Suppress finalization.
        GC.SuppressFinalize(this);
    }

    protected void MailSendCompleted(MailToDoItem mailToDoItem, AsyncCompletedEventArgs e)
    {
        string err = "";
        //_logger.Info($"[Send Completed]: {JsonConvert.SerializeObject(mailToDoItem)}");
        //using (var _conn = new SqlConnection(_connStr))
        //{
        //    var result = e.Error != null ? "F" : "Y";
        //    var errMsg = e.Error != null ? e.Error.ToString() : "";
        //    _conn.Execute(@"UPDATE MailToDo SET Status = @Status, ErrMessage = @ErrMessage
        //                , SendUser = @SendUser, SendTime = @SendTime WHERE SeqNo = @SeqNo"
        //                            , new
        //                            {
        //                                Status = result,
        //                                mailToDoItem.SeqNo,
        //                                SendUser = "SYS",
        //                                SendTime = DateTime.Now,
        //                                ErrMessage = errMsg
        //                            });
        //}
    }
}

public class EmailSetting
{
    public string SmtpServer { get; set; } = GlobalClass.appsettings("MailServer:smtp_host");
    public int SmtpPort { get; set; } = int.Parse(GlobalClass.appsettings("MailServer:smtp_port"));
    public string Account { get; set; } = GlobalClass.appsettings("MailServer:smtp_username");
    public string Password { get; set; } = GlobalClass.appsettings("MailServer:smtp_password");
}
