using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using LHDN.CRM.Models.ViewModels;
using System.Net;
using LHDN.CRM.BC.Common;
using System.Globalization;
using System.Linq;

namespace LHDN.CRM.BC.Services
{
    public class EmailService
    {
        private Repositories.EmailRepository repo = new Repositories.EmailRepository();

        string strSubject = String.Empty;
        string TemplateName = String.Empty;
        string strContent = String.Empty;
        string strTemplateHTML = String.Empty;
        Dictionary<string, string> dicBookmarkValue = new Dictionary<string, string>();
        bool blnEmpty = true;
        string strKategoryContent = String.Empty;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="email">Sent To Email</param>
        /// <param name="CCEmail">CC Email</param>
        /// <param name="Id">RefTableId</param>
        public long SendEmailNotification(List<string> lstEmailTo, List<string> lstEmailCC, int TemplateId,string CreatedBy, long reftableId, DateTime now)
        {
            string strEmailCC = string.Empty;
            string strEmailTo = getEmailFromList(lstEmailTo);
            if (lstEmailCC.Count > 0)
            {
               strEmailCC = getEmailFromList(lstEmailCC);
            }
            else
            {
                strEmailCC = null;
            }
    
            string strEmailFrom = AdminService.ParameterSettings.Where(x => x.ParameterID == 5).Select(x => x.ParameterValue).FirstOrDefault();

            // 'Get Email Content from template 
            GetHTMLParsedContent(TemplateId, reftableId, TemplateName, strSubject, strContent);
            EmailQueueViewModel emailqueue = new EmailQueueViewModel();
            emailqueue.From = strEmailFrom;
            emailqueue.Body = strContent;
            emailqueue.Subject = strSubject;
            emailqueue.CC = strEmailCC;
            emailqueue.To = strEmailTo;
            emailqueue.CreatedBy = CreatedBy;
            emailqueue.LastUpdatedBy = CreatedBy;
           
            long i = repo.SendEmailNotification(emailqueue, now);

            return i;
        }

        public long SendEmail(List<string> lstEmailFrom, List<string> lstEmailTo, List<string> lstEmailCC, List<string> lstEmailBCC, int TemplateId, string strEmailContent, string strEmailSubject, long reftableId, string CreatedBy,  DateTime now, int AttachmentTableType = 0 , long RefAttachmentTableID = 0)
        {
            string strEmailFrom = getEmailFromList(lstEmailFrom);
            string strEmailTo = getEmailFromList(lstEmailTo);
            string strEmailCC = getEmailFromList(lstEmailCC);
            string strEmailBCC = getEmailFromList(lstEmailBCC);
            // 'Get Email Content from template 
            GetHTMLParsedContent(TemplateId, reftableId, strEmailContent);
            EmailQueueViewModel emailqueue = new EmailQueueViewModel();
            emailqueue.Body = strContent;
            emailqueue.Subject = strEmailSubject;
            emailqueue.From = strEmailFrom;
            emailqueue.To = strEmailTo;
            emailqueue.CC = strEmailCC;
            emailqueue.BCC = strEmailBCC; 
            emailqueue.CreatedBy = CreatedBy;
            emailqueue.LastUpdatedBy = CreatedBy;
            emailqueue.AttachmentTableType = AttachmentTableType;
            emailqueue.RefAttachmentTableID = RefAttachmentTableID;

            long i = repo.SendEmailNotification(emailqueue, now);

            return i;
        }

        private string getEmailFromList(List<string> lstEmailTo)
        {
            string strEmailTo = "";
            foreach (var email in lstEmailTo)
            {
                if (!string.IsNullOrEmpty(email.Trim()))
                {
                    if (!string.IsNullOrEmpty(strEmailTo))
                    {
                        strEmailTo += ";";
                    }
                    strEmailTo += email;
                }
            }
            return strEmailTo;
        }

        public string GetHTMLParsedContent(int templateId,long reftableId, string TemplateName,string EmailSubject,string EmailContent, string strLoginName = "")
        {
            //bool result = false;
            Dictionary<string, string> _dicBookmarkValue = new Dictionary<string, string>();
            if (templateId > 0)
            {
                // 'Get template and bookmark Values
                _dicBookmarkValue = GetBookmarkValue(templateId, reftableId, _dicBookmarkValue);

                if (templateId == (int)Constant.EmailTemplate.ActBackOfficeReviewNotification)
                    templateId = (int)Constant.EmailTemplate.BackOfficeReviewNotification;

                if (templateId == (int)Constant.EmailTemplate.PrintSlipKedatangan || templateId == (int)Constant.EmailTemplate.PrintPenerimaanDoc)
                    _dicBookmarkValue.Add("Kaunter Officer Name", strLoginName);
            }

            DataSet dSet = new DataSet();
            dSet = repo.GetCorrespondenceTemplateByID(templateId);

            if (dSet != null && dSet.Tables.Count > 0)
            {
                foreach (DataTable row in dSet.Tables)
                {
                    strSubject = row.Rows[0]["Subject"].ToString();
                    TemplateName = row.Rows[0]["TemplateName"].ToString();
                    strTemplateHTML = templateId == (int)Constant.EmailTemplate.PrintSlipKedatangan ? WebUtility.HtmlDecode(row.Rows[0]["TemplateHTML"].ToString()) : WebUtility.HtmlDecode(row.Rows[0]["TemplateHTML"].ToString());
                }
            }

            //'GetContent from template and bookmark values
            strContent = GetContentFromTemplate(strTemplateHTML, _dicBookmarkValue);

            return strContent;
        }

        public bool GetHTMLParsedContent(int templateId, long reftableId, string strEmailContent)
        {
            bool result = false;
            Dictionary<string, string> _dicBookmarkValue = new Dictionary<string, string>();
            if (templateId > 0)
            {
                // 'Get template and bookmark Values
                _dicBookmarkValue = GetBookmarkValue(templateId, reftableId, _dicBookmarkValue);
            }
              
            //'GetContent from template and bookmark values
            strContent = GetContentFromTemplate(strEmailContent, _dicBookmarkValue);

            return result;
        }

        public Dictionary<string,string> GetBookmarkValue(int templateId,long reftableId, Dictionary<string, string> _dicBookmarkValue)
        {
            string strKey = String.Empty ;
            string strValue = String.Empty;
            bool isActAssign = false;
            //Dictionary<string, string> dicBookmarkValue ;
            DataSet dTbl = new DataSet();
            List<CaseKategoriDocReceivedViewModel> lst = new List<CaseKategoriDocReceivedViewModel>();

            if (templateId == (int)Constant.EmailTemplate.ActBackOfficeReviewNotification)
            {
                isActAssign = true;
                templateId = (int)Constant.EmailTemplate.BackOfficeReviewNotification;
                dTbl = repo.GetBookmarkValue(templateId, reftableId, isActAssign);
            }
            else
            {
                dTbl = repo.GetBookmarkValue(templateId, reftableId, isActAssign);
            }           

            if (dTbl != null && dTbl.Tables.Count > 0)
            {
                foreach (DataTable row in dTbl.Tables)
                {
                    for(var i=0; i< dTbl.Tables[0].Rows.Count; i++)
                    {
                        strKey = row.Rows[i]["BookmarkKey"].ToString();
                        strValue = row.Rows[i]["BookmarkValue"].ToString();
                        if(strValue =="")
                        {
                            strValue = "-";
                            _dicBookmarkValue.Add(strKey, strValue);
                        }
                        else
                        {
                            _dicBookmarkValue.Add(strKey, strValue);
                        }                     
                    }
                }
            }

            //lst = repo.GetCaseKategory(reftableId);
            //if(lst !=null && lst.Count > 0)
            //{
            //    strKategoryContent = GetKategoryContentToHTMLFormat(lst);
     
            //    dicBookmarkValue.Add("DokumenTable", strKategoryContent);
            //}
            //else
            //{
            //    dicBookmarkValue.Add("DokumenTable", "-");
            //}

           // GetHTMLParsedContent ="<table><th>" + ValueType + "<th>"

            return _dicBookmarkValue;
        }

        public string GetContentFromTemplate(string templateHtml, Dictionary<string, string> _dicBookmarkValue)
        {
            Regex regex = new Regex(@"(\[)(\[)(.*?)(\])(\])", RegexOptions.IgnoreCase);
            dicBookmarkValue = _dicBookmarkValue;
            MatchEvaluator matchEval = new MatchEvaluator(BookmarkMatchEvaluator);
            
            return regex.Replace(templateHtml, matchEval);
        }

        public string BookmarkMatchEvaluator(Match match)
        {
            string key = match.Groups[3].Value;
            if (dicBookmarkValue.ContainsKey(key))
            {
                return dicBookmarkValue[key];
            }
            else
            {
                if(blnEmpty)
                {
                    return "<!--bookmark='" + key + "'-->";
                }
                else
                {
                    return "[" + key + "]";
                }
               
            }  
        }

        public List<EmailQueueViewModel> GetEmailQueueList()
        {
            List<EmailQueueViewModel> lstEmailQueue = new List<EmailQueueViewModel>();

            lstEmailQueue = repo.GetEmailQueueList();

            return lstEmailQueue;
        }

        public void InsertEmailHist(long lngEmailQueueID)
        {
            repo.InsertEmailHist(lngEmailQueueID);
        }

        public void DeleteEmailQueue(long lngEmailQueueID)
        {
            repo.DeleteEmailQueue(lngEmailQueueID);
        }

        public void UpdateEmailFailAttempt(EmailQueueViewModel objEmail)
        {
            repo.UpdateEmailFailAttempt(objEmail);
        }

        public string GetHTMLParsedContentForPreview(int templateId, long reftableId, string TemplateName, string EmailSubject, string EmailContent,byte[] qrcode,DateTime qrdatetime ,string strBranchName, string strLoginName = "", int tabletype =0,string DocKategoryActID = "")
        {
            //bool result = false;
            Dictionary<string, string> _dicBookmarkValue = new Dictionary<string, string>();
            DataSet dTbl = new DataSet();
            CaseViewModel vmCase = new CaseViewModel();
            if (templateId > 0)
            {
                // 'Get template and bookmark Values
                dicBookmarkValue = GetBookmarkValue(templateId, reftableId, _dicBookmarkValue);

                string s = Convert.ToBase64String(qrcode);
                _dicBookmarkValue.Add("QR Code", s);
                _dicBookmarkValue.Add("QR Code Date", qrdatetime.ToString());
                _dicBookmarkValue.Add("Kaunter Officer Name", strLoginName);
                _dicBookmarkValue.Add("Kaunter", strBranchName);
                _dicBookmarkValue.Add("Activity Dicetak Oleh", strLoginName);
                _dicBookmarkValue.Add("Kes Dicetak Oleh", strLoginName);

                List<CaseKategoriDocReceivedViewModel> lst = new List<CaseKategoriDocReceivedViewModel>();
                List<CaseKategoriDocReceivedViewModel> templst = new List<CaseKategoriDocReceivedViewModel>();
                
                if (DocKategoryActID != "" && DocKategoryActID != null)
                {
                    List<string> KategoryDocActID = DocKategoryActID.Split(',').ToList<string>(); 
                    foreach (var a in KategoryDocActID)
                    {
                        if(KategoryDocActID.Count > 1)
                        {
                            templst = repo.GetAllKategoryDocumentByRefID(Convert.ToInt64(a), tabletype, DocKategoryActID);
                            lst.AddRange(templst);

                        }
                        else
                        {
                            lst = repo.GetAllKategoryDocumentByRefID(Convert.ToInt64(a), tabletype, DocKategoryActID);
                        }
                       
                    }

                    if (lst != null && lst.Count > 0)
                    {
                        strKategoryContent = GetKategoryContentToHTMLFormat(lst);

                        _dicBookmarkValue.Add("DokumenTable", strKategoryContent);
                    }
                    else
                    {
                        _dicBookmarkValue.Add("DokumenTable", "<div style='font-family:arial'><p>Tiada Rekod</p></div>");
                    }

                }
                else
                {
                    lst = repo.GetAllKategoryDocumentByRefID(reftableId, tabletype, DocKategoryActID);
                    if (lst != null && lst.Count > 0)
                    {
                        strKategoryContent = GetKategoryContentToHTMLFormat(lst);

                        _dicBookmarkValue.Add("DokumenTable", strKategoryContent);
                    }
                    else
                    {
                        _dicBookmarkValue.Add("DokumenTable", "<div style='font-family:arial'><p>Tiada Rekod</p></div>");
                    }

                }

            }

            DataSet dSet = new DataSet();
            dSet = repo.GetCorrespondenceTemplateByID(templateId);

            if (dSet != null && dSet.Tables.Count > 0)
            {
                foreach (DataTable row in dSet.Tables)
                {
                    strSubject = row.Rows[0]["Subject"].ToString();
                    TemplateName = row.Rows[0]["TemplateName"].ToString();
                    if (templateId == (int)Constant.EmailTemplate.PrintPenerimaanDoc)
                    {
                        strTemplateHTML = templateId == (int)Constant.EmailTemplate.PrintPenerimaanDoc ? WebUtility.HtmlDecode(row.Rows[0]["TemplateHTML"].ToString()) : row.Rows[0]["TemplateHTML"].ToString();
                    }
                    else
                    {
                        strTemplateHTML = templateId == (int)Constant.EmailTemplate.PrintActPenerimaanDoc ? WebUtility.HtmlDecode(row.Rows[0]["TemplateHTML"].ToString()) : row.Rows[0]["TemplateHTML"].ToString();
                    }
                }
            }

            //'GetContent from template and bookmark values
            strContent = GetContentFromTemplate(strTemplateHTML, _dicBookmarkValue);

            return strContent;
        }

        public string GetKategoryContentToHTMLFormat(List<CaseKategoriDocReceivedViewModel> GetCaseKategory)
        {
            string html = "";
            string TarikhDocument = "";
            string TahunTaksiran = "";

            foreach (var a in GetCaseKategory)
            {
                foreach(var b in a.KategoriDocReceived)
                {
                    html += "<div style='page-break-after:always;font-size:12px;font-family:arial;margin-bottom:20px'><b><span> " + b.KategoriDocName + "<span></b><table class='table' style='margin-top:10px;border:1px solid #CCC;border-collapse:collapse; width:100%;table-layout:fixed;font-size:11px;font-family:arial'><thead style='font-size:12px'><tr><td width='30%' class='col-md-3' style='border:1px solid #CCC;padding:10px; text-align: left;'><b>Nama Dokumen </b></td><td width='20%' class='col-md-3' style='border:1px solid #CCC;padding:10px; text-align: left;'><b>Tarikh Dokumen</b></td><td width='20%' class='col-md-3' style='border:1px solid #CCC;padding:10px; text-align: left;'><b>Tahun Taksiran</b></td><td width='30%' class='col-md-3' style='border:1px solid #CCC;padding:10px; text-align: left;word-break:break-word;'><b>Catatan</b></td></thead>";

                    foreach (var c in b.ActDocReceived)
                    {
                        if (c.ActivityID == a.ActivityID && c.DocListID == b.DocListID)
                        {
                            if (c.TarikhDokumen.HasValue)
                            {
                                TarikhDocument = c.TarikhDokumen.Value.ToString("dd MMM yyyy");
                            }
                            else
                            {
                                TarikhDocument = "-";
                            }

                            if(c.Remarks == "")
                            {
                                c.Remarks = "-";
                            }

                            if(c.TahunTaksiran == null)
                            {
                                TahunTaksiran = "-";
                            }
                            else
                            {
                                TahunTaksiran = c.TahunTaksiran.ToString("yyyy");
                            }
                               
                            html += "<tbody style='font-size:12px'><tr><td style='border:1px solid #CCC;padding:10px; text-align: left;'>" + c.DocName + "</td><td style='border:1px solid #CCC;padding:10px; text-align: left;'>" + TarikhDocument + "</td><td style='border:1px solid #CCC;padding:10px; text-align: left;'> " + TahunTaksiran + "</td><td style='border:1px solid #CCC;padding:10px; text-align: left;word-break:break-word;word-wrap: break-word;'>" + c.Remarks + "</td></tr></tbody>";
                        }
                      
                    }
                    html += "</table></div>";
                }

            }
            return html;
        }
    }
}
