using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.OracleClient;
using System.Diagnostics;
using EjadaCSLoader;

public partial class Business_Monitor : System.Web.UI.Page
{
    public static bool start = false;
    public string load_type = "AA";
    //public static int count = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SecurityAgent.AuthenticateArchive();
            loadJobs();
            loadJobNames();
            loadFileTypes();
            btnStart.Enabled = false;
            start = false;
        }
        //lblError.Text = "";
    }

    private void loadJobs()
    {
        try
        {
            string DBConnection = Helper.dbConnection();

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

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

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "APPLICATION_MONITOR.Get_Job_Status";

            oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_job_type", 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_res_type", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_res_msg", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;


            oracom.Parameters["p_lang"].Value = "EN";
            oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();
            oracom.Parameters["p_job_type"].Value = "L";

            OracleDataAdapter da = new OracleDataAdapter(oracom);
            DataSet ds = new DataSet();
            da.Fill(ds);

            GridView1.DataSource = ds;
            GridView1.DataBind();

            oracon.Close();
            // Label2.Text += "1 ";
            StackTrace stackTrace = new StackTrace();
            string method = stackTrace.GetFrame(1).GetMethod().Name;
            if (start)
            {
                if (method.Contains("Timer1_Tick"))
                {

                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        if (dr["Status"].ToString().Equals("STARTED"))
                        {
                            lblError.ForeColor = System.Drawing.Color.DarkMagenta;
                            lblError.Text = "Job Started";
                            btnStart.Enabled = false;
                            break;
                        }
                        else if (dr["Status"].ToString().Equals("RUNNING"))
                        {
                            lblError.ForeColor = System.Drawing.Color.DarkViolet;
                            lblError.Text = "Job in Progress...";
                            btnStart.Enabled = false;
                            break;
                        }
                        else
                        {

                            //count++;
                            //if (count > 3)
                            //    lblError.Text = "";
                            //else
                            //{
                            lblError.ForeColor = System.Drawing.Color.DarkGreen;
                            lblError.Text = "Job completed";
                            btnStart.Enabled = true;
                            //}
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    private void loadJobNames()
    {
        string DBConnection = Helper.dbConnection();

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "LOOKUP_GETTER.get_list_jobtype";

        oracom.Parameters.Add("p_job_type", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_load_type", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_jobs", OracleType.Cursor).Direction = ParameterDirection.Output;

        oracom.Parameters["p_job_type"].Value = "L";
        oracom.Parameters["p_load_type"].Value = load_type;

        OracleDataAdapter da = new OracleDataAdapter(oracom);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlJobs.DataSource = ds;
        ddlJobs.DataBind();

        ddlJobs.Items.Insert(0, "------ Job Name ------");
        oracon.Close();


        //string DBConnection = Helper.dbConnection();

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

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

        //oracom.CommandType = CommandType.StoredProcedure;
        //oracom.CommandText = "LOOKUP_GETTER.Get_Job_Names";

        //oracom.Parameters.Add("p_job_type", OracleType.VarChar).Direction = ParameterDirection.Input;
        //oracom.Parameters.Add("p_jobs", OracleType.Cursor).Direction = ParameterDirection.Output;

        //oracom.Parameters["p_job_type"].Value = "L";

        //OracleDataAdapter da = new OracleDataAdapter(oracom);
        //DataSet ds = new DataSet();
        //da.Fill(ds);

        //ddlJobs.DataSource = ds;
        //ddlJobs.DataBind();

        //ddlJobs.Items.Insert(0, "------ Job Name ------");
        //oracon.Close();
    }

    private void loadFileTypes()
    {
        ddlFiles.Items.Clear();
        if (ddlJobs.SelectedIndex > 0)
        {
            string DBConnection = Helper.dbConnection();

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

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

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "LOOKUP_GETTER.Get_Job_File_Types";

            oracom.Parameters.Add("p_job_name", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_file_types", OracleType.Cursor).Direction = ParameterDirection.Output;

            oracom.Parameters["p_job_name"].Value = ddlJobs.SelectedValue;

            OracleDataAdapter da = new OracleDataAdapter(oracom);
            DataSet ds = new DataSet();
            da.Fill(ds);
            oracon.Close();
            ddlFiles.DataSource = ds;
            ddlFiles.DataBind();
        }
        ddlFiles.Items.Insert(0, "------ File Type ------");
        
    }

    private bool startJob(ref string error)
    {
        string DBConnection = Helper.dbConnection();

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "APPLICATION_MONITOR.Start_Load_Job";

        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_file_type", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_all_files", 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_res_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 = ddlJobs.SelectedValue;
        oracom.Parameters["p_file_date"].Value = DatePicker1.date;
        if (chkAll.Checked)
        {
            oracom.Parameters["p_file_type"].Value = OracleString.Null;
            oracom.Parameters["p_all_files"].Value = "Y";
        }
        else
        {
            oracom.Parameters["p_file_type"].Value = ddlFiles.SelectedValue;
            oracom.Parameters["p_all_files"].Value = "N";
        }
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        error = oracom.Parameters["p_res_msg"].Value.ToString();
        if (a == "0")
            return true;
        else
            return false;
    }

    public string GetCSName(string job_name)
    {
        DataTable dtRes = new DataTable();
        try
        {
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);

            OracleCommand oraCom = new OracleCommand();
            oraCom.CommandText = "select * from application_jobs where job_name ='" + job_name + "'";
            oraCom.Connection = oracon;
            OracleDataAdapter da = new OracleDataAdapter(oraCom);


            da.Fill(dtRes);
            if (dtRes.Rows.Count > 0 && dtRes.Rows[0]["LOAD_TYPE"] as string == "DLL")
                return dtRes.Rows[0]["directroy"] as string;
                else
                    return "DBJOB";

        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
            return "EXCEPTION";
           
        }
    }

    protected void btnStart_Click(object sender, EventArgs e)
    {

        ExceptionUtility.LogEvent_Errors(0, "", "btnStart_Click", "Start");
    
        if (DatePicker1.date.Length == 0)
        {
            lblError.Text = "please enter a date";
        }
        else if (ddlJobs.SelectedIndex == 0)
        {
            lblError.Text = "please select the job";
        }
        else
        {

            var item = ddlFiles.SelectedItem;

            string CSName= GetCSName(ddlJobs.SelectedValue);// != "DBJOB")

            // Applicaiton job
            string strRespMsg = ""; //this will hold the response message details

            if (CSName == "EXCEPTION")
                return;
            else if (CSName == "DBJOB")
            {
                // Database job
                //count = 0;
                start = true;
                string error = "";
                bool saved = startJob(ref error);
                if (saved)
                {
                    lblError.ForeColor = System.Drawing.Color.DarkGreen;
                    lblError.Text = "Job Started";
                }
                else
                {
                    lblError.Text = error;
                }
                // END DB Job
            }
            else if (CSName.Length > 1)
            {

                try
                {
                    EJCSLoader objEJCSLoader = new EJCSLoader();

                    lblError.ForeColor = System.Drawing.Color.DarkGreen;
                    lblError.Text = "Application Running";
                    ExceptionUtility.LogEvent_Errors(0, "", "btnStart_Click", "Before dll Call");

                    objEJCSLoader.Load_CS(ConfigurationSettings.AppSettings["CSLoader"], DatePicker1.date, CSName, out strRespMsg);
                    lblError.Text = strRespMsg;

                    ExceptionUtility.LogEvent_Errors(0, "", "btnStart_Click", "dll Call Response" + strRespMsg);
                }
                catch (Exception ex)
                {
                    ExceptionUtility.LogException(ex); ;
                    lblError.Text = "Exception: Please Refer to application Log";
                }

            }
            else
                lblError.Text = "Failed to find relevent job.";
        

            loadJobs();
        }
        ExceptionUtility.LogEvent_Errors(0, "", "btnStart_Click", "End");
    }

    public void Load_File_Type()
    {
        if (GetCSName(ddlJobs.SelectedValue) != "DBJOB" || rdtypeConfig.Checked)
        {
            LoadAll.Visible = false;
            ddlFiles.Enabled = false;
            return;
        }
        else
        {
            LoadAll.Visible = true;
            ddlFiles.Enabled = true;
        }

        loadFileTypes();
        btnStart.Enabled = false;
        if (ddlFiles.Items.Count == 2)
        //if (ddlJobs.SelectedValue.Equals("LOAD_MDS")
        //    || ddlJobs.SelectedValue.Equals("LOAD_VISA")
        //        || ddlJobs .SelectedValue .Equals ("LOAD_AMEX")
        //            || ddlJobs .SelectedValue .Equals ("LOAD_VISA_REPORT")
        //                || ddlJobs.SelectedValue.Equals("LOAD_BANCS")
        //                    || ddlJobs.SelectedValue.Equals("LOAD_REPL"))
        {
            chkAll.Enabled = false;
            ddlFiles.Enabled = true;
        }
        else
        {
            chkAll.Enabled = true;
        }
        chkAll.Checked = false;
    }

    protected void ddlJobs_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.Load_File_Type();
    }

    protected void rdtypeConfig_CheckedChanged(object sender, EventArgs e)
    {
        btnStart.Enabled = true;
        this.Load_Type();
    }

    protected void rdtypeRegular_CheckedChanged(object sender, EventArgs e)
    {
        this.Load_Type();
    }

    public void Load_Type()
    {
        if (rdtypeConfig.Checked)
        {
            load_type = "DLL";
        }
        else if (rdtypeRegular.Checked)
        {
            load_type = "AA";
        }

        this.loadJobNames();
        this.Load_File_Type();
    }

    protected void ddlFiles_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlFiles.SelectedIndex > 0)
            btnStart.Enabled = true;
        else
            btnStart.Enabled = false;
        DatePicker1.date = "";
    }

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        loadJobs();
    }

    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        if (chkAll.Checked)
        {
            ddlFiles.Enabled = false;
            if(ddlJobs.SelectedIndex > 0)
                btnStart.Enabled = true;
        }
        else
        {
            ddlFiles.Enabled = true;
            ddlFiles.SelectedIndex = 0;
            btnStart.Enabled = false;
        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = e.Row.DataItem as DataRowView;
            if (drv["status"].ToString().Equals("RUNNING") || drv["status"].ToString().Equals("STARTED"))
                e.Row.BackColor = System.Drawing.Color.LightBlue;
            else
                e.Row.BackColor = System.Drawing.Color.Transparent;
        }
    }
}
