using Microsoft.Extensions.Options;
using Backend.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Threading.Tasks;
using BackendWorkerService.Services.Interface;
using Microsoft.Extensions.Logging;

namespace BackendWorkerService.Services.Implement
{
    public class SendEmailService : ISendEmailService
    {
        private readonly ILogger<SendEmailService> logger;
        private readonly IOptions<SMTPConfig> _options;

        private SMTPConfig smtp;

        public SendEmailService(ILogger<SendEmailService> logger, IOptions<SMTPConfig> options)
        {
            this.logger = logger;
            smtp = options.Value;
        }

        public bool Send(int id, List<string> recipientEmails, string subject, string content)
        {
            try
            {
                logger.LogInformation("【SendEmailSMSService】【Email開始寄送】[任務編號]:{0}", id);

                MailMessage MyMail = new MailMessage();

                MyMail.SubjectEncoding = System.Text.Encoding.UTF8;//郵件標題編碼
                MyMail.BodyEncoding = System.Text.Encoding.UTF8; //郵件內容編碼
                MyMail.IsBodyHtml = true; //是否使用html格式

                var mailFrom = $"FIC IBMS管理系統通知 <{smtp.UserName}>";

                MyMail.From = new System.Net.Mail.MailAddress(mailFrom); //寄件人
                foreach (var email in recipientEmails)
                {
                    MyMail.To.Add(email); //設定收件者Email
                }

                MyMail.Subject = subject; //主題
                MyMail.Body = content; //設定信件內容

                //讀取 SMTP Config
                SmtpClient MySMTP = new SmtpClient(smtp.Host, smtp.Port);
                MySMTP.EnableSsl = smtp.EnableSsl;
                MySMTP.Credentials = new System.Net.NetworkCredential(smtp.UserName, smtp.Password);

                try
                {
                    MySMTP.Send(MyMail);
                    MySMTP.Dispose();
                    MyMail.Dispose(); //釋放資源

                    logger.LogInformation("【SendEmailSMSService】【Email寄送成功】[任務編號]:{0}", id);
                    return true;
                }
                catch(Exception exception)
                {
                    logger.LogError("【SendEmailSMSService】【Email寄送失敗】[任務編號]:{0}", id);
                    logger.LogError("【SendEmailSMSService】【Email寄送失敗】[Exception]:{0}", exception.ToString());
                    return false;
                }
            }
            catch (Exception exception)
            {
                logger.LogError("【SendEmailSMSService】【Email寄送失敗】[任務編號]:{0}", id);
                logger.LogError("【SendEmailSMSService】【Email寄送失敗】[Exception]:{0}", exception.ToString());
                throw;
                //return false;
            }

        }
    }
}