namespace LAPS_WATCHER.App_Data
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net.Mail;
    using System.Text;

    class VendorMail
    {
        public static string SendMail(string TransId, string Method, string errormessage, string envimnt)
        {

            SmtpClient smtpClient = new SmtpClient();
            MailMessage message = new MailMessage();
            //MailAddress fromAddress = null;
            //string tomail = "";
            try
            {
                //string qry = @"SELECT mt.templatename,mt.subject,mt.body,mt.createdby,mt.createddate,mt.modifiedby,mt.modifieddate,mt.active,mt.mailtemplateid FROM mail_template_master mt where  mt.active=1 and mt.mailtemplateid=" + ConfigurationSettings.AppSettings["errormailtemplateid"].ToString();
                //DataTable mailTemplate = db.GetDataTable(dbCon,qry,null);
                //if (mailTemplate.Rows.Count <= 0)
                //    return "";

                //StringBuilder sb = new StringBuilder(mailTemplate.Rows[0]["body"].ToString());
                //sb.Replace("$$tranid", TransId);
                //sb.Replace("$$datetime", DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss"));
                //qry = @"Select jm.title jobtitle,lm.title lottitle,jwfm.stagename_alias stagename,lt.transactionid from lot_transaction lt 
                //      left outer join lot_master lm on lt.lotid = lm.lotid left outer join job_master jm on jm.jobid = lm.jobid
                //      left outer join job_workflow_master jwfm on jwfm.jobworkflowid = lt.jobworkflowid where lt.transactionid = @@TransId and jwfm.merged_lot = 0
                //      union all
                //      Select jm.title jobtitle, lm.batchname lottitle, jwfm.stagename_alias stagename, lt.transactionid from lot_transaction lt
                //      left outer join lot_batch lm on lt.batchid = lm.batchid left outer join job_master jm on jm.jobid = lm.jobid
                //      left outer join job_workflow_master jwfm on jwfm.jobworkflowid = lt.jobworkflowid where lt.transactionid = @@TransId and jwfm.merged_lot = 1";
                //DataTable JobDet = db.GetDataTable(dbCon, qry.Replace("@@TransId", TransId), null);
                //var ErrorContent = "";
                //if (JobDet.Rows.Count > 0)
                //{

                //    ErrorContent = @"<p style='font-weight:bold'>Error Details.</p>";
                //    ErrorContent += "<table style='border: 1px solid silver;'>";
                //    ErrorContent += @"<tr><th  style='border: 1px solid silver;'>" + "<font color='#555555'>Job Title</font></th>" +
                //                               "<th  style='border: 1px solid silver;'> <font color='#555555'>Lot Title</font></th>" +
                //                               "<th  style='border: 1px solid silver;'> <font color='#555555'>Stage Name</font></th>" +
                //                               "<th  style='border: 1px solid silver;'> <font color='#555555'>Method</font></th>" +
                //                               "<th  style='border: 1px solid silver;'> <font color='#555555'>Error</font></th></tr>";
                //    foreach (DataRow dd in JobDet.Rows)
                //    {
                //        ErrorContent += "<tr><td  style='border: 1px solid silver;'><font color='#555555'>" + dd["jobtitle"].ToString() + "</font></td>" +
                //                            "<td  style='border: 1px solid silver;'><font color='#555555'>" + dd["lottitle"].ToString() + "</font></td>" +
                //                            "<td  style='border: 1px solid silver;'><font color='#555555'>" + dd["stagename"].ToString() + "</font></td>" +
                //                            "<td  style='border: 1px solid silver;'><font color='#555555'>" + Method + "</font></td>" +
                //                            "<td  style='border: 1px solid silver;'><font color='#555555'>" + errormessage + "</font></td></tr>";
                //    }



                //    ErrorContent += "</table>";
                //}
                //if(ErrorContent != "")
                //    sb.Replace("$$errormessage", ErrorContent);
                //else
                //    sb.Replace("$$errormessage", errormessage  + " <br/> Method : " + Method);

                //string b = WebUtility.HtmlDecode(sb.ToString());
                //message.Body = b;
                //message.Subject = mailTemplate.Rows[0]["subject"].ToString() + " Environment " + envimnt;
                //tomail = ConfigurationSettings.AppSettings["to_mail_list"].ToString();
                //message.To.Add(new MailAddress(tomail));
                //var dt1 = db.GetDataTable(dbCon, "select emailid from mail_template_mailid md left outer join user_master um on um.userid = md.userid " +
                //                        "where mtid = " + ConfigurationSettings.AppSettings["errormailtemplateid"].ToString() + "",null);
                //if (dt1.Rows.Count > 0)
                //{
                //    for (int i = 0; i <= dt1.Rows.Count - 1; i++)
                //    {
                //        if (dt1.Rows[i][0].ToString() != "")
                //            message.CC.Add(new MailAddress(dt1.Rows[i][0].ToString()));
                //    }
                //}
                //fromAddress = new MailAddress(ConfigurationSettings.AppSettings["from_mail"], "LAPS-PDY Error Mail " + "_" + envimnt.ToUpper());
                //smtpClient.Host = ConfigurationSettings.AppSettings["from_mail_host"];
                //smtpClient.EnableSsl = true;
                //smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["from_mail_port"]);
                //NetworkCredential myCredential = new NetworkCredential(ConfigurationSettings.AppSettings["from_mail"], ConfigurationSettings.AppSettings["from_mail_password"]);
                //smtpClient.Credentials = myCredential;
                //message.From = fromAddress;
                //MailMessage mail = new MailMessage();
                //message.IsBodyHtml = true;
                //smtpClient.Send(message);
                return null;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return null;
            }
        }

        public static void LogError(string _message)
        {
            string _Location;
            _Location = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Logs\\";
            if (!(Directory.Exists(_Location + DateTime.Today.Year)))
            {
                Directory.CreateDirectory(_Location + DateTime.Today.Year);
            }
            _Location = _Location + DateTime.Today.Year + "\\";
            if (!(Directory.Exists(_Location + DateTime.Today.ToString("MMMM"))))
            {
                Directory.CreateDirectory(_Location + DateTime.Today.ToString("MMMM"));
            }
            _Location = _Location + DateTime.Today.ToString("MMMM") + "\\";
            _Location = _Location + DateTime.Today.ToString("dd") + ".txt";

            try
            {
                StreamWriter _sw = new StreamWriter(_Location, true);
                _sw.Write(_message);
                _sw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void LogWrite(string str, string Method, Exception objException = null)
        {
            Exception _Exception;
            string _Error = "";
            _Exception = objException;

            if (_Exception != null)
            {
                _Error = "===========================" + Environment.NewLine;
                _Error = _Error + "Date         :" + DateTime.Today.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + Environment.NewLine;
                _Error = _Error + "Method       :" + Method + Environment.NewLine;
                _Error = _Error + "Error Desc   :" + _Exception.Message + Environment.NewLine;
                _Error = _Error + "Source       :" + _Exception.Source + Environment.NewLine;
                _Error = _Error + "Line No      :" + _Exception.StackTrace + Environment.NewLine;
                _Error = _Error + "=============================";
            }
            else
            {
                _Error = "===========================" + Environment.NewLine;
                _Error = _Error + "Date         :" + DateTime.Today.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + Environment.NewLine;
                _Error = _Error + "Method       :" + Method + Environment.NewLine;
                _Error = _Error + "msg          :" + str + Environment.NewLine;
                _Error = _Error + "=============================";
            }
            LogError(_Error);
        }
        public static void CallErrorMessage(string tranid, string jobworkflowid, string jobid, string batch_lot_id, string MethodName, string errorMessage, int ErrorCode, string ursa_url, Exception objException = null)
        {
            //BLDatamanipulation db1 = new BLDatamanipulation();
            //DBContext db = new DBContext();
            //insert_lot_comments(Convert.ToString(errorMessage), "", tranid.ToString(), "D", jobworkflowid, jobid, batch_lot_id);
            //string sqry = string.Format("update lot_transaction set lotstatus = '{0}' where transactionid={1}", "D", tranid.ToString());
            //db1.InsertQuery(db, sqry, null);
            //if (ursa_url != "") MethodName = MethodName + " ursa_url : " + ursa_url;
            //if (ErrorCode != 0) MethodName = MethodName + " ErrorCode : " + ErrorCode;
            //LogWrite(errorMessage, MethodName, objException);
            //SendMail(tranid, MethodName, errorMessage, LAPS_SERVICE_CONTROLLER.Global.Enviroinment);
        }
        public static int insert_lot_comments(string comment, string FileName, string transid, string doption, string tostage, string jobid, string lotid)
        {
            //BLDatamanipulation db1 = new BLDatamanipulation();
            //DBContext db = new DBContext();
            //db1.GetDataTable(db, "select * from insert_lot_comments ('" + comment + "','" + FileName + "','" + transid + "','" + doption + "','" + tostage + "','" + 0 + "','" + 0 + "')", null);
            return 0;
        }
    }
}
