using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using WK_KLI_LAPS_Service.App_Data;
using WK_KLI_LAPS_Service.Models;
using WK_KLI_LAPS_Service.Models.Master;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WK_KLI_LAPS_Service.Controllers.Common.SendMail
{
    public interface ISendMailService
    {
        bool FindbyMailId_user(string mailid);
        string sendmail(string emailid, string emailtype, Appsettings _appsettings);
    }
    public class SendMailService : ISendMailService
    {
        UserRepository oUserRepository = new UserRepository();
        CommonRepository oCommonRepository = new CommonRepository();
        MasterRepository oMasterRepository = new MasterRepository();


        public string sendmail(string email, string emailtype, Appsettings _appsettings)
        {
            string s = "Invalid Email ID";
            // string userEmailid = "";

            string mailSucess = string.Empty;
            StringBuilder sbody = new StringBuilder();
            try
            {

                if (email != null || email != "")
                {
                    userModel userList = new userModel();
                    userList = (userModel)oUserRepository.FindByEmail(email);
                    string emailportid = Startup.Configuration.GetValue<string>("AppSettings:emailportid");
                    SmtpClient client = new SmtpClient();
                    client.UseDefaultCredentials = false;
                    client.Host = _appsettings.emailhost;
                    client.EnableSsl = true;
                    client.Port = Convert.ToInt32(emailportid);
                    System.Net.NetworkCredential myCredential = new System.Net.NetworkCredential(_appsettings.emailusername, _appsettings.emailpassword);
                    client.Credentials = myCredential;
                    //get mailtemplate values
                    mailtemplateModel omailmodal = new mailtemplateModel();
                    MailMessage mailMessage = new MailMessage();
                    mailMessage.From = new MailAddress(_appsettings.emailusername);
                    if (emailtype == "forgotpassword")
                    {
                        mailtemplateModel mailTemplateList = new mailtemplateModel();
                        mailTemplateList.mailtemplateid = _appsettings.forgotpassword;
                        string input = JsonConvert.SerializeObject(mailTemplateList);
                        string data = oMasterRepository.GetScalarValue("mailtemplate", input);
                        //if (data.Count() > 0 && data[0] != null)
                        if (data != null)
                        {
                            try
                            {
                                omailmodal = JsonConvert.DeserializeObject<JArray>(data).ToObject<List<mailtemplateModel>>().FirstOrDefault();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                                omailmodal = null;
                            }
                        }
                        else
                            omailmodal = null;
                        //mailtemplateModel mailTemplateList = new mailtemplateModel();
                        //mailTemplateList.mailtemplateid = _appsettings.forgotpassword;
                        //string input = JsonConvert.SerializeObject(mailTemplateList);
                        //var data = oMasterRepository.GetById("mailtemplate", input);
                        ////if (data.Count() > 0 && data[0] != null)
                        //    if (data != null)
                        //    omailmodal = JsonConvert.DeserializeObject<JArray>(data.ToString()).ToObject<List<mailtemplateModel>>().FirstOrDefault();
                        //else
                        //    omailmodal = null;
                    }
                    if (omailmodal != null)
                    {
                        sbody.Append(omailmodal.body + " </br>");
                        sbody.Append("<a href=" + _appsettings.emailbodylinkforgotpassword + "?email=" + email.ToString());
                        sbody.Append(">" + _appsettings.emailbodylinkname + "</a>");
                        string mailBody = sbody.ToString();
                        sbody = oCommonRepository.formatMailContent(mailBody, userList);
                        if (emailtype == "forgotpassword")
                        {
                            if (email != string.Empty)
                                mailMessage.To.Add(email);
                        }
                        // mail cc list
                        var input8 = new { mailtemplateid = _appsettings.forgotpassword };
                        var jsonstr8 = JsonConvert.SerializeObject(input8);
                        var dt3 = App_Data.CommonRepository.ExecuteSP_ReturnList2("spusermasterselect", jsonstr8, "getbymailtemplateid");
                        if (dt3 != null)
                        {
                            var d_data2 = JsonConvert.DeserializeObject<object>(dt3.ToString());
                            JArray p_data2 = JArray.Parse(d_data2.ToString());

                            dynamic json1 = JsonConvert.DeserializeObject(p_data2.ToString());
                            foreach (var s1 in json1)
                            {
                                if (!string.IsNullOrEmpty(s1["emailid"].ToString())) {
                                    if (email != s1["emailid"].ToString())
                                    {
                                        mailMessage.CC.Add(new MailAddress(s1["emailid"].ToString()));
                                    }
                                   
                                }
                                
                            }
                        }

                        mailMessage.Body = sbody.ToString();
                        mailMessage.IsBodyHtml = true;
                        mailMessage.Subject = omailmodal.subject;
                        try
                        {
                            client.Send(mailMessage);
                            s = "success";
                        }

                        catch (Exception e2)
                        {
                            s = e2.Message;
                            if (s.ToLower().Contains(':'))
                            {
                                string[] tokens = s.Split(':');
                                s = tokens[2].ToString();
                            }
                        }
                    }
                    else
                    {
                        s = "Email template not available";
                    }

                }
                else
                {
                    s = "Invalid Email ID";
                }
            }
            catch (Exception ex)
            {
                oCommonRepository.ErrorLog(ex);
            }
            return s;
        }


        public bool FindbyMailId_user(string mailid)
        {
            var res = oUserRepository.FindbyMailidForUser(mailid);
            return res;
        }
        
    }
}
