using Microsoft.Extensions.Options;
using SolarPower.Models;
using SolarPower.Services.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Threading.Tasks;

namespace SolarPower.Services
{
    public class SendEmailService : ISendEmailService
    {
        private readonly IOptions<SMTPConfig> _options;

        private SMTPConfig smtp;
        
        public SendEmailService(IOptions<SMTPConfig> options)
        {
            smtp = options.Value;
        }

        public bool Send(List<string> recipientEmails, string subject, string content)
        {
            MailMessage MyMail = new MailMessage();

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

            MyMail.From = new System.Net.Mail.MailAddress(smtp.UserName); //寄件人
            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(); //釋放資源

                return true;
            }
            catch (Exception ex)
            {
                //_log.LogError("【SendEmailSMSService】 " + noticeInfo.Recipient_email + "寄送信件失敗");

                return false;
            }

        }
    }
}
