using System;
using System.Data;
using System.Xml;
using System.Text;
using System.Linq;
using System.Net.Mail;
using System.Globalization;
using System.Configuration;
using System.Data.OracleClient;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Newtonsoft.Json.Linq;

namespace EjadaGSettle
{
    public class EJGenSettle
    {
        public string filedate, filename, parameters, response;

        public static string dbConnection()
        {
            string tempConnectionString = ConfigurationSettings.AppSettings["DBConnection"];
            return decryptConnectionString(tempConnectionString);
        }

        [DllImport("EncDecDLL.dll")]
        private static extern void rijndael_decrypt(string src, StringBuilder string_filled_in_dll);

        private static string decryptConnectionString(string strEncryptedString)
        {
            string src = DecryptLibrary.DecryptLibrary.DecryptData(strEncryptedString);
            StringBuilder string_filled_in_dll = new StringBuilder();
            EJGenSettle.rijndael_decrypt(src, string_filled_in_dll);
            return string_filled_in_dll.ToString();
        }
        
        public static string Decrypt_String(string input)
        {
            string Base24Input = DecryptLibrary.DecryptLibrary.DecryptData(input);
            string oldPath = Environment.GetEnvironmentVariable("path");
            bool found = oldPath.Contains(ConfigurationManager.AppSettings["EncDllPath"]);
            if (!found)
                System.Environment.SetEnvironmentVariable("Path", ConfigurationManager.AppSettings["EncDllPath"] + oldPath);

            StringBuilder output = new StringBuilder();
            rijndael_decrypt(Base24Input, output);

            return output.ToString();
        }

        public static bool OracleError(string strError)
        {
            bool error = false;
            if (strError.Contains("ORA-"))
                error = true;
            else
                error = false;
            return error;
        }

        private bool GenSettleEntry(string filedate, ref string error)
        {
            parameters = "";
            try
            {
                string DBConnection = dbConnection();

                OracleConnection oracon = new OracleConnection(DBConnection);
                oracon.Open();

                OracleCommand oracom = new OracleCommand();
                oracom.Connection = oracon;

                ExceptionUtility.LogException(0, "", "EJGenSettle", "Start GenSettleEntry", "");
                oracom.CommandType = CommandType.StoredProcedure;
                oracom.CommandText = "pos_settelment_monitor.Gen_Rpt_POSSettl";

                oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
                oracom.Parameters.Add("p_job_name", OracleType.VarChar).Direction = ParameterDirection.Input;
                oracom.Parameters.Add("p_file_date", OracleType.VarChar).Direction = ParameterDirection.Input;
                oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
                oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;
                oracom.Parameters.Add("p_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
                oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

                oracom.Parameters["p_job_name"].Value = "GEN_RPT_POSSETTL";
                //parameters = "p_job_name-GEN_RPT_POSSETTL:";

                oracom.Parameters["p_file_date"].Value = filedate;
                oracom.Parameters["p_lang"].Value = "EN";
                oracom.Parameters["p_current_uid"].Value = "1";

                oracom.ExecuteNonQuery();
                oracon.Close();
                string a = oracom.Parameters["p_res_code"].Value.ToString();
                error = oracom.Parameters["p_res_msg"].Value.ToString();
                if (a == "0")
                {
                    ExceptionUtility.LogException(0, "", "EJGenSettle (Success)", "Gen_Rpt_POSSettl_Response", error);
                    return true;
                }
                else
                {
                    ExceptionUtility.LogException(9, "", "EJGenSettle (Failed)", "Gen_Rpt_POSSettl_Response", error);
                    return false;
                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.LogException(ex, "", "EJGenSettle (Error)", "Gen_Rpt_POSSettl_Response", error);
                return false;
            }

            ExceptionUtility.LogException(0, "", "EJGenSettle", "End GenSettleEntry", "");
        }

        public void StartJob()
        {
            string[] reader = Console.ReadLine().Split(' ');
            if (reader != null)
            {
                filedate = reader[0];
                filename = reader[1];
                
                string error = "";
                string read_input = filedate + ", " + filename;
                ExceptionUtility.LogException(0, "", "EJGenSettle", "Read File", read_input);
                bool saved = this.GenSettleEntry(filedate, ref error);
                if (saved)
                {
                    response = "Process completed";
                    ExceptionUtility.LogException(9, "", "EJGenSettle (Success)", "GenSettleEntry Response", response);
                }
                else
                {
                    if (OracleError(error))
                    {
                        response = "An Error Occured!";
                        ExceptionUtility.LogException(9, "", "EJGenSettle (Error)", "GenSettleEntry Response", response);
                    }
                    else
                    {
                        response = error;
                        ExceptionUtility.LogException(9, "", "EJGenSettle (Error)", "GenSettleEntry Response", response);
                    }
                }

                //Console.Write("\nPress any key to continue... ");
                //Console.ReadLine();
            }
        }

        public static string GetMerchantEmail(string TerminalID)
        {
            string TermId = "", Email = "", result;
            DataTable dtRes = new DataTable();

            string DBConnection = dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);

            ExceptionUtility.LogException(0, "", "EJGenSettle", "Start GetMerchantEmail", "");
            OracleCommand oraCom = new OracleCommand();
            oraCom.CommandText = @" select dvl.term_id as Term_Id, ma.email_address as Email_Address from merchant_address ma,device_link_tbl dvl where ma.client_no=dvl.client_number
                    and dvl.term_id='" + TerminalID + "' and dvl.status='001' and ma.email_address is not null";

            oraCom.Connection = oracon;
            OracleDataAdapter da = new OracleDataAdapter(oraCom);

            da.Fill(dtRes);

            if (dtRes.Rows.Count >= 1)
            {
                TermId = dtRes.Rows[0]["Term_Id"].ToString();
                Email = dtRes.Rows[0]["Email_Address"].ToString();
            }

            result = TermId + ", " + Email;
            ExceptionUtility.LogException(0, "", "EJGenSettle", "End GetMerchantEmail", result);

            return Email;
        }

        public static string Send_Email(string ToEmail, string Subject, string Body, string ccEmail, string AttachmentPath)
        {
            ExceptionUtility.LogException(0, "", "EJGenSettle", "Start Send_Email", "");

            var EmailHost = ConfigurationSettings.AppSettings["EmailHost"] as string;
            var EmailHostPort = ConfigurationSettings.AppSettings["EmailHostPort"] as string;
            var Email_User_id = ConfigurationSettings.AppSettings["Email_User_id"] as string;
            //var Email_Pass =    System.Web.Configuration.WebConfigurationManager.AppSettings["Email_Pass"] as string;
            var Email_Pass = Decrypt_String(ConfigurationSettings.AppSettings["Email_Pass"]);

            try
            {
                SmtpClient client = new SmtpClient
                {
                    Host = EmailHost,
                    Port = Int32.Parse(EmailHostPort),
                    //EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials = new System.Net.NetworkCredential(Email_User_id, Email_Pass),
                    //Timeout = 10000,
                };

                MailMessage mail = new MailMessage(Email_User_id, ToEmail, Subject, Body);

                ExceptionUtility.LogException(0, "", "EJGenSettle", "Send_Email", "ToEmail:" + ToEmail + "Subject:" + Subject);

                if (!string.IsNullOrWhiteSpace(ccEmail))
                {
                    ExceptionUtility.LogException(0, "", "EJGenSettle", "Send_Email", "ccEmail : " + ccEmail);
                    mail.CC.Add(ccEmail);
                }
                if (!string.IsNullOrWhiteSpace(AttachmentPath))
                {
                    ExceptionUtility.LogException(0, "", "EJGenSettle", "Send_Email", "AttachmentPath : " + AttachmentPath);
                    Attachment attachItem = new Attachment(AttachmentPath);
                    mail.Attachments.Add(attachItem);

                }
                client.Send(mail);

                ExceptionUtility.LogException(0, "", "EJGenSettle", "Send_Email", "ToEmail : " + ToEmail + " ccEmail : " + ccEmail + ",Body : " + Body);
                
                string response = ("Email Sent Sucessfully to ") + ToEmail;
                ExceptionUtility.LogException(0, "", "EJGenSettle", "End Send_Email", response);

                return response;
            }
            catch (Exception e)
            {
                //Console.WriteLine("Could not end email\n\n" + e.ToString());
                ExceptionUtility.LogException(e, "", "EJGenSettle", "Send_Email", "");

                string error = "Failed To Send Email : " + ToEmail + " ccEmail : " + ccEmail + " Exception : Check log for more Details";
                ExceptionUtility.LogException(0, "", "EJGenSettle", "End Send_Email", error);

                return error;
            }
        }

        static void Main(string[] args)
        {
            EJGenSettle eJGen = new EJGenSettle();
            eJGen.StartJob();
        }
    }
}
