using Abp.Specifications;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net.Mail;
using System.Text;
using UnivateProperties_API.Context;
using UnivateProperties_API.Helpers;
using UnivateProperties_API.Model.Communication;
using UnivateProperties_API.Model.ProcessFlow;
using UnivateProperties_API.Model.Timeshare;
using UnivateProperties_API.Model.Users;

namespace UnivateProperties_API.Repository.Communication
{
    public interface IMailRepository
    {
        void ContactUs(MailModel mm);
        void EnquireNow(MailModel mm);
        void AddRecipient(MailRecipient rec);
        List<MailRecipient> GetMailRecipients();
        MailRecipient GetMailRecipientById(int id);
        void UpdateMailRecipient(MailRecipient rec);
        void DeleteMailRecipient(int id);
    }

    public class MailRepository : IMailRepository
    {
        private readonly DataContext _dbContext;

        public MailRepository(DataContext db)
        {
            _dbContext = db;              
        }

        public MailRepository()
        {
        }        

        public void ContactUs(MailModel mm)
        {
            var recipients = _dbContext.MailRecipients.Where(x => x.RecipientUsage == "ContactUs").Where(y => y.IsDeleted == false).ToList();            
            string body = _dbContext.Templates.Where(x => x.Name == "ContactUs").Where(y => y.IsDeleted == false).FirstOrDefault().Body; 

            body = body.Replace("[FULLNAME]", mm.Name);
            body = body.Replace("[USEREMAIL]", mm.Email);
            body = body.Replace("[USERCELLPHONE]", mm.Phone);
            body = body.Replace("[PROPERTYREF]", mm.Property);
            body = body.Replace("[USERMESSAGE]", mm.Message);

            string toList = "";
            int emailCount = 0;
            foreach (var recipient in recipients)
            {
                toList += recipient.RecipientMail + ", ";
                emailCount++;
            }

            if (toList.Length > 0)
            {
                if (emailCount == 1)
                    toList = toList.Substring(0, toList.Length - 2);
                else
                    toList = toList.Substring(0, toList.Length - 2);
            }

            var host = _dbContext.Hosts.FirstOrDefault();
            using (SmtpClient smtp = new SmtpClient(host.Host))
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(toList);
                mail.Subject = "Uni-Vate - New Contact Request";
                mail.Body = body;
                mail.IsBodyHtml = true;
                mail.BodyEncoding = Encoding.ASCII;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.Sender = new MailAddress(host.User, "UniVate Properties");
                mail.From = new MailAddress(mm.Email, mm.Name);

                smtp.UseDefaultCredentials = host.NeedsAuthorize;
                smtp.Credentials = host.GetNetworkCredential();
                smtp.EnableSsl = host.UseSSL;
                smtp.Send(mail);
            }            
        }

        public void EnquireNow(MailModel mm)
        {
            var recipients = _dbContext.MailRecipients.Where(x => x.RecipientUsage == "EnquireNow").Where(y => y.IsDeleted == false).ToList();
            string body = _dbContext.Templates.Where(x => x.Name == "EnquireNow").Where(y => y.IsDeleted == false).FirstOrDefault().Body;
            var property = _dbContext.Properties.Where(x => x.Id == Convert.ToInt32(mm.Property)).FirstOrDefault();

            body = body.Replace("[FULLNAME]", mm.Name);
            body = body.Replace("[USEREMAIL]", mm.Email);
            body = body.Replace("[USERCELLPHONE]", mm.Phone);
            body = body.Replace("[PROPERTYID]", mm.Property);
            body = body.Replace("[PROPERTYNAME]", property.PropertyName);
            body = body.Replace("[PROPERTYREF]", property.PropertyRef);
            body = body.Replace("[PROPERTYPRICE]", property.Price.ToString());
            body = body.Replace("[USERMESSAGE]", mm.Message);

            string toList = "";
            int emailCount = 0;
            foreach (var recipient in recipients)
            {
                toList += recipient.RecipientMail + ", ";
                emailCount++;
            }

            if (toList.Length > 0)
            {
                if (emailCount == 1)
                    toList = toList.Substring(0, toList.Length - 2);
                else
                    toList = toList.Substring(0, toList.Length - 2);
            }

            var host = _dbContext.Hosts.FirstOrDefault();
            using (SmtpClient smtp = new SmtpClient(host.Host))
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(toList);
                mail.Subject = "Uni-Vate - Enquiry to view property";
                mail.Body = body;
                mail.IsBodyHtml = true;
                mail.BodyEncoding = Encoding.ASCII;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.Sender = new MailAddress(host.User, "UniVate Properties");
                mail.From = new MailAddress(mm.Email, mm.Name);

                smtp.UseDefaultCredentials = host.NeedsAuthorize;
                smtp.Credentials = host.GetNetworkCredential();
                smtp.EnableSsl = host.UseSSL;
                smtp.Send(mail);
            }            
        }

        public void ForgotPassword(Individual toPerson, string link)
        {
            string body = "<div style=\"margin: 5px\">" + 
                           "<h4>Dear " + toPerson.FullName + "</h4>" +
                           "<h4>There has been a request to reset your password. If this is incorrect please send an email to info@univateproperties.co.za</h4>" +
                           "<h4>Once your password has been reset you can use the username "+ toPerson.User.Username + " and the new password to log in.</h4>" +
                           "<div>" +
                           "<h4><a href='" + link + "'>Click here</a> to reset your password.</h4>" +
                           "<br />"+
                           "<h4>Thank You</h4>" +
                           "<h4>Team Uni-Vate</h4>" +
                           "</div>" +
                           "</div>";

            var host = _dbContext.Hosts.FirstOrDefault();

            using (SmtpClient smtp = new SmtpClient(host.Host))
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(new MailAddress(toPerson.Email, toPerson.FullName));
                mail.Subject = "Uni-Vate - Password Reset Request";
                mail.Body = body;
                mail.IsBodyHtml = true;
                mail.BodyEncoding = Encoding.ASCII;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.Sender = new MailAddress(host.User, "UniVate Properties");
                mail.From = mail.Sender;

                smtp.UseDefaultCredentials = host.NeedsAuthorize;
                smtp.Credentials = host.GetNetworkCredential();
                smtp.EnableSsl = host.UseSSL;
                smtp.Send(mail);
            }
        }

        public void WeekOfferMadeOwner(TimeshareWeek week, BidItem bid)
        {
            var recipients = _dbContext.MailRecipients.Where(x => x.RecipientUsage == "WeekOfferMade-Owner").Where(y => y.IsDeleted == false).ToList();
            string body = _dbContext.Templates.Where(x => x.Name == "WeekOfferMade-Owner").Where(y => y.IsDeleted == false).FirstOrDefault().Body;
            
            body = body.Replace("[OWNER]", week.DisplayOwner);
            body = body.Replace("[RESORTNAME]", week.ResortName);
            body = body.Replace("[UNITNUMBER]", week.UnitNumber);
            body = body.Replace("[MODULE]", week.Module);
            body = body.Replace("[OFFERMADE]", bid.Amount.ToString());
            body = body.Replace("[FULLNAME]", bid.BidMaker.Display);
            body = body.Replace("[USEREMAIL]", bid.BidMaker.Email);
            body = body.Replace("[USERCELLPHONE]", bid.BidMaker.CellNumber);
            body = body.Replace("[USERTELEPHONE]", bid.BidMaker.Telephone);
            body = body.Replace("[USERCOMMENT]", bid.Comment);

            string toList = "";
            int emailCount = 0;
            foreach (var recipient in recipients)
            {
                toList += recipient.RecipientMail + ", ";
                emailCount++;
            }

            if (toList.Length > 0)
            {
                if (emailCount == 1)
                    toList = toList.Substring(0, toList.Length - 2);
                else
                    toList = toList.Substring(0, toList.Length - 2);
            }

            var host = _dbContext.Hosts.FirstOrDefault();
            using (SmtpClient smtp = new SmtpClient(host.Host))
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(toList);
                mail.Subject = "Uni-Vate - New Contact Request";
                mail.Body = body;
                mail.IsBodyHtml = true;
                mail.BodyEncoding = Encoding.ASCII;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.Sender = new MailAddress(host.User, "UniVate Properties");
                mail.From = mail.Sender;

                smtp.UseDefaultCredentials = host.NeedsAuthorize;
                smtp.Credentials = host.GetNetworkCredential();
                smtp.EnableSsl = host.UseSSL;
                smtp.Send(mail);
            }
        }

        public void WeekOfferMadeUser(TimeshareWeek week, BidItem bid)
        {
            //var recipients = _dbContext.MailRecipients.Where(x => x.RecipientUsage == "WeekOfferMade-User").Where(y => y.IsDeleted == false).ToList();

            string body = _dbContext.Templates.Where(x => x.Name == "WeekOfferMade-User").Where(y => y.IsDeleted == false).FirstOrDefault().Body; ;

            body = body.Replace("[OWNER]", week.DisplayOwner);
            body = body.Replace("[RESORTNAME]", week.ResortName);
            body = body.Replace("[UNITNUMBER]", week.UnitNumber);
            body = body.Replace("[MODULE]", week.Module);
            body = body.Replace("[OFFERMADE]", bid.Amount.ToString());
            body = body.Replace("[FULLNAME]", bid.BidMaker.Display);
            body = body.Replace("[USEREMAIL]", bid.BidMaker.Email);
            body = body.Replace("[USERCELLPHONE]", bid.BidMaker.CellNumber);
            body = body.Replace("[USERTELEPHONE]", bid.BidMaker.Telephone);
            body = body.Replace("[USERCOMMENT]", bid.Comment);



            var host = _dbContext.Hosts.FirstOrDefault();
            using (SmtpClient smtp = new SmtpClient(host.Host))
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(bid.BidMaker.Email);
                mail.Subject = "Uni-Vate - New Contact Request";
                mail.Body = body;
                mail.IsBodyHtml = true;
                mail.BodyEncoding = Encoding.ASCII;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.Sender = new MailAddress(host.User, "UniVate Properties");
                mail.From = mail.Sender;

                smtp.UseDefaultCredentials = host.NeedsAuthorize;
                smtp.Credentials = host.GetNetworkCredential();
                smtp.EnableSsl = host.UseSSL;
                smtp.Send(mail);
            }
        }

        public void WeekOfferMadeAdmin()
        {
            
        }

        public void WeekLoadedAgent(TimeshareWeek week)
        {
            string body = _dbContext.Templates.Where(x => x.Name == "WeekLoaded-Agent").Where(y => y.IsDeleted == false).FirstOrDefault().Body;
            var recipients = _dbContext.MailRecipients.Where(x => x.RecipientUsage == "WeekLoaded-Agent").Where(y => y.IsDeleted == false).ToList();

            body = body.Replace("[FULLNAME]", week.DisplayOwner);
            body = body.Replace("[RESORTNAME]", week.ResortName);
            body = body.Replace("[UNITNUMBER]", week.UnitNumber);
            body = body.Replace("[MODULE]", week.Module);

            string toList = "";
            int emailCount = 0;
            foreach (var recipient in recipients)
            {
                toList += recipient.RecipientMail + ", ";
                emailCount++;
            }

            if (toList.Length > 0)
            {
                if (emailCount == 1)
                    toList = toList.Substring(0, toList.Length - 2);
                else
                    toList = toList.Substring(0, toList.Length - 2);
            }

            var host = _dbContext.Hosts.FirstOrDefault();
            using (SmtpClient smtp = new SmtpClient(host.Host))
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(toList);
                mail.Subject = "Uni-Vate - Password Reset Request";
                mail.Body = body;
                mail.IsBodyHtml = true;
                mail.BodyEncoding = Encoding.ASCII;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.Sender = new MailAddress(host.User, "UniVate Properties");
                mail.From = mail.Sender;

                smtp.UseDefaultCredentials = host.NeedsAuthorize;
                smtp.Credentials = host.GetNetworkCredential();
                smtp.EnableSsl = host.UseSSL;
                smtp.Send(mail);
            }
        }

        public void WeekLoadedOwner(TimeshareWeek week)
        {
            string body = _dbContext.Templates.Where(x => x.Name == "WeekLoaded-Owner").Where(y => y.IsDeleted == false).FirstOrDefault().Body;
            var recipients = _dbContext.MailRecipients.Where(x => x.RecipientUsage == "WeekLoaded-Owner").Where(y => y.IsDeleted == false).ToList();

            body = body.Replace("[FULLNAME]", week.DisplayOwner);
            body = body.Replace("[RESORTNAME]", week.ResortName);
            body = body.Replace("[UNITNUMBER]", week.UnitNumber);
            body = body.Replace("[MODULE]", week.Module);

            string toList = "";
            int emailCount = 0;
            foreach (var recipient in recipients)
            {
                toList += recipient.RecipientMail + ", ";
                emailCount++;
            }

            if (toList.Length > 0)
            {
                if (emailCount == 1)
                    toList = toList.Substring(0, toList.Length - 2);
                else
                    toList = toList.Substring(0, toList.Length - 2);
            }

            var host = _dbContext.Hosts.FirstOrDefault();
            using (SmtpClient smtp = new SmtpClient(host.Host))
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(toList);
                mail.Subject = "Uni-Vate - Password Reset Request";
                mail.Body = body;
                mail.IsBodyHtml = true;
                mail.BodyEncoding = Encoding.ASCII;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.Sender = new MailAddress(host.User, "UniVate Properties");
                mail.From = mail.Sender;

                smtp.UseDefaultCredentials = host.NeedsAuthorize;
                smtp.Credentials = host.GetNetworkCredential();
                smtp.EnableSsl = host.UseSSL;
                smtp.Send(mail);
            }
        }

        public void AddRecipient(MailRecipient rec)
        {
            if (MyCommon.IsValidEmail(rec.RecipientMail))
            {
                _dbContext.MailRecipients.Add(rec);
                _dbContext.SaveChanges();
            }
            else
            {
                throw new Exception();
            }
            
        }

        public List<MailRecipient> GetMailRecipients()
        {
            return _dbContext.MailRecipients.Where(x => x.IsDeleted == false).ToList();
        }

        public MailRecipient GetMailRecipientById(int id)
        {
            return _dbContext.MailRecipients.Where(x => x.Id == id).FirstOrDefault(); 
        }

        public void UpdateMailRecipient(MailRecipient rec)
        {
            var recipient = _dbContext.MailRecipients.Where(x => x.Id == rec.Id).FirstOrDefault();

            if (recipient.RecipientMail != rec.RecipientMail)
            {
                recipient.RecipientMail = rec.RecipientMail;
            }

            if (recipient.RecipientName != rec.RecipientName)
            {
                recipient.RecipientName = rec.RecipientName;
            }

            if (recipient.RecipientUsage != rec.RecipientUsage)
            {
                recipient.RecipientUsage = rec.RecipientUsage;
            }


            _dbContext.MailRecipients.Update(recipient);
            _dbContext.SaveChanges();
        }

        public void DeleteMailRecipient(int id)
        {
            var rec = _dbContext.MailRecipients.Where(x => x.Id == id).FirstOrDefault();        
            _dbContext.MailRecipients.Remove(rec);
            _dbContext.SaveChanges();
        }
    }
}