using System;
using System.Collections.Generic;
using BMA.EHR.Recurit.Exam.Service.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml;
using System.Data;
using System.Net;
using System.Net.Mail;

namespace BMA.EHR.Recurit.Exam.Service.Services
{
    public class MailService
    {
        #region " Fields "

        private readonly ApplicationDbContext _context;
        private readonly IConfiguration _configuration;
        private readonly IWebHostEnvironment _webHostEnvironment;

        #endregion

        #region " Constructors "

        public MailService(ApplicationDbContext context,
                            IConfiguration configuration,
                            IWebHostEnvironment webHostEnvironment)
        {
            _context = context;
            _configuration = configuration;
            _webHostEnvironment = webHostEnvironment;
        }

        public static IConfigurationRoot Configuration
        {
            get
            {
                return new ConfigurationBuilder()
                                  .SetBasePath(Directory.GetCurrentDirectory())
                                  .AddJsonFile("appsettings.json")
                                  .Build();
            }
        }

        #endregion

        #region " Methods "

        public void SendMailToUser(string subject, string body, string receiver)
        {
            try
            {
                var server = _configuration["Mail:Server"];
                var user = _configuration["Mail:User"];
                var password = _configuration["Mail:Password"];
                var port = _configuration["Mail:Port"];
                var from = _configuration["Mail:MailFrom"];

                var client = new SmtpClient(server, Convert.ToInt32(port));
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(user, password);
                client.EnableSsl = true;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;

                var mail = new MailMessage();
                mail.From = new MailAddress(from, "ทรัพยากรบุคคลกรุงเทพมหานคร");
                mail.To.Add(receiver);
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = true;
                client.Send(mail);
            }
            catch
            {
                throw;
            }
        }
        #endregion
    }
}