using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Data;
using System.Diagnostics;
using EjadaCSGenParser;
using EjadaCSLoader;
using EjadaFileLoaderLicenceVerifier;
using System.Threading;
using System.Configuration;

public partial class Monitor : System.Web.UI.Page
{
    public static bool start = false;

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            loadJobs();
            loadJobNames();
            loadFileTypes();
            btnStart.Enabled = false;
            start = false;
        }
    }

    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.Text = "Job Started";
                            Notifications.showMessage("Job Started", this, Notifications.errorMessage, false);
                            btnStart.Enabled = false;
                            break;
                        }
                        else if (dr["Status"].ToString().Equals("RUNNING"))
                        {
                            //lblError.Text = "Job in Progress...";
                            Notifications.showMessage("Job in Progress...", this, Notifications.errorMessage, false);
                            btnStart.Enabled = false;
                            break;
                        }
                        else
                        {

                            //count++;
                            //if (count > 3)
                            //    lblError.Text = "";
                            //else
                            //{
                            //lblError.Text = "Job completed";
                            Notifications.showMessage("Job completed", this, Notifications.errorMessage, false);
                            btnStart.Enabled = true;
                            //}
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.Cells[7].Text == "Successful")
        {
            e.Row.Cells[7].ForeColor = System.Drawing.Color.Green;
        }
        else if (e.Row.Cells[7].Text == "Response")
        {
            e.Row.Cells[7].ForeColor = System.Drawing.Color.Black;
        }
        else
        {
            e.Row.Cells[7].ForeColor = System.Drawing.Color.Red;
        }
    }

    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_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 = Helper.getDate(txtjdate.Text);
        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;
            Notifications.showMessage(ex.Message, this, Notifications.errorMessage, false);
            return "EXCEPTION";

        }
    }

    protected void btnftab_Click(object sender, EventArgs e)
    {
        Response.Redirect("Monitor.aspx");
    }

    protected void btnrtab_Click(object sender, EventArgs e)
    {
        Response.Redirect("MonitorRecon.aspx");
    }

    protected void btnhtab_Click(object sender, EventArgs e)
    {
        Response.Redirect("MonitorHist.aspx");
    }

    protected void btnStart_Click(object sender, EventArgs e)
    {
        this.Start();
    }

    public void Start()
    {
        ExceptionUtility.LogEvent_Errors(0, "", "btnStart_Click", "Start");

        if (txtjdate.Text.Length == 0)
        {
            //lblError.Text = "please enter a date";
            Notifications.showMessage("Please Enter a Date", this, Notifications.errorMessage, false);
        }
        else if (ddlJobs.SelectedIndex == 0)
        {
            //lblError.Text = "please select the job";
            Notifications.showMessage("Please Select the Job", this, Notifications.errorMessage, false);
        }
        else
        {
            string parameters = "";
            try
            {
                string[] Arr = ddlJobs.SelectedValue.Split('-');
                string path = Arr[1];
                string[] Arr1 = Arr[0].Split('_');
                string channel_name = Arr1[1];
                //string path = exe_dir.Substring(0, exe_dir.LastIndexOf('\\'));
                string strRespMsg;

                //System.Diagnostics.Process.Start(exe_dir, " " + channel_name + " " + Helper.getDate(txtjdate.Text) + " " + path);
                //System.Diagnostics.Process.Start("F:\\Taly\\Loader\\OASIS\\Execute_OASIS.bat");
                EJCSLoader objEJCSLoader = new EJCSLoader();
                parameters = path + " " + Helper.getDate(txtjdate.Text) + " " + channel_name + " ";
                objEJCSLoader.Load_CS(path, Helper.getDate(txtjdate.Text), channel_name, out strRespMsg);
                parameters += strRespMsg;
                //lblError.Text = strRespMsg;
                Notifications.showMessage(strRespMsg, this, Notifications.errorMessage, false);
                ExceptionUtility.LogEvent_Errors(0, "", "loadJobs", parameters);
            }
            catch (Exception ex)
            {
                ExceptionUtility.LogException(ex, "loadJobs", parameters, "", "");
            }
            loadJobs();
        }
        ExceptionUtility.LogEvent_Errors(0, "", "btnStart_Click", "End");
    }

    protected void ddlJobs_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (GetCSName(ddlJobs.SelectedValue) != "DBJOB")
        {
            File_Type.Visible = false;
            Chk_All.Visible = false;
        }
        else
        {
            File_Type.Visible = true;
            Chk_All.Visible = true;
        }
            
        loadFileTypes();
        btnStart.Enabled = false;

        if (ddlFiles.Items.Count > 2)
        {
            if (ddlJobs.SelectedValue.Equals("LOAD_PPMS") || ddlJobs.SelectedValue.Equals("LOAD_MDS") || ddlJobs.SelectedValue.Equals("LOAD_MIGS"))
            {
                chkAll.Enabled = false;
            }
            else
            {
                chkAll.Enabled = true;
            }

            Chk_All.Visible = true;
            File_Type.Visible = true;
        }
        else
        {
            chkAll.Enabled = false;
        }

        chkAll.Checked = false;
    }

    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_PreRender(object sender, EventArgs e)
    {
        if (GridView1.Rows.Count > 0)
        {
            GridView1.UseAccessibleHeader = true;
            GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
    }
}