using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.OracleClient;
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.Diagnostics;
using System.IO;

public partial class GWFileSummary : System.Web.UI.Page
{
    public int page_id = 0;
    public string table_name = "", filenumber;
    string url = "";
    static int intCount = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        //table_name = "business_rules";
        //url = HttpContext.Current.Request.Url.AbsolutePath;
        //string[] urlArr = url.Split('/');
        //url = urlArr[2] + "/" + urlArr[3];
        //page_id = loadPageIDs(url);
        //if (!IsPostBack)
        //{
        //    SecurityAgent.AuthenticateArchive();
            
        //    ExceptionUtility.LogException(0, "", "5", "Page_Load", "");
        //}
    }
    private int loadPageIDs(string URL)
    {
        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 = "lookup_getter.get_pages";

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


            oracom.Parameters["p_url"].Value = URL;

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

            oracon.Close();
            return int.Parse(ds.Tables[0].Rows[0]["pid"].ToString());
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "lookup_getter.get_pages","", "loadPageIDs", "URL: " + URL);
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
            return 0;
        }
    }
    

    private void loadFileNames()
    {
        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 = "Generate_VAT_Invoice.Get_GWFileName";

            oracom.Parameters.Add("P_FromDate", OracleType.VarChar, 250).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_ToDate", OracleType.VarChar, 250).Direction = ParameterDirection.Input;

            oracom.Parameters.Add("P_FileName", OracleType.Cursor).Direction = ParameterDirection.Output;

            oracom.Parameters["P_FromDate"].Value = dtPostDateFrom.date;
            oracom.Parameters["P_ToDate"].Value = dtPostDateTo.date;
            
            OracleDataAdapter da = new OracleDataAdapter(oracom);
            DataSet ds = new DataSet();
            da.Fill(ds);

            ddlFiles.DataSource = ds;
            ddlFiles.DataBind();
            ddlFiles.Items.Insert(0, "------ Files ------");

            oracon.Close();
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "Generate_VAT_Invoice.Get_GWFileName", "", "loadFileNames", "");
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
        }
    }

    private void loadResult( int pageSize, int pageNumber)
    {
        string parameters = "";
        try
        {
            string currentMethod = "";
            StackTrace stackTrace = new StackTrace();
            currentMethod = stackTrace.GetFrame(1).GetMethod().Name;
            string DBConnection = Helper.dbConnection();

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

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

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "Generate_VAT_Invoice.GetGWFileSummary";

            oracom.Parameters.Add("P_FromDate", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_ToDate", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_FileName", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

            //if (channelID.Length != 0)
            //{
            //    parameters = "p_rc_code-" + channelID;
            //    oracom.Parameters["p_rc_code"].Value = channelID;
            //}
            //else
            //    oracom.Parameters["p_rc_code"].Value = OracleNumber.Null;
            //if (eventID.Length != 0)
            //{
            //    parameters = parameters + "p_re_code-" + eventID;
            //    oracom.Parameters["p_re_code"].Value = eventID;
            //}
            //else
            //    oracom.Parameters["p_re_code"].Value = OracleNumber.Null;

            oracom.Parameters["P_FromDate"].Value = dtPostDateFrom.date;
            oracom.Parameters["P_ToDate"].Value = dtPostDateTo.date;
            if (ddlFiles.SelectedIndex > 0)
                oracom.Parameters["P_FileName"].Value = ddlFiles.SelectedItem.Text;
            else
                oracom.Parameters["P_FileName"].Value = OracleString.Null;

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

            oracon.Close();

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

            if (ds.Tables[0].Rows.Count != 0)
            {
                this.loadVATResult();
                pnlVATResult.Visible = true;
            }

            if (currentMethod.Contains("btnSearch_Click"))
                ExceptionUtility.LogException(0, "BUSINESS_RULES_EDITOR.Get_Business_Rules","132.1", "loadResult", parameters );
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "BUSINESS_RULES_EDITOR.Get_Business_Rules","132.1", "loadResult", parameters );
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
        }
    }

    public void Clear()
    {
        lblError.Text = "";

        GridView1.DataSource = null;
        GridView1.DataBind();
        pnlResult.Visible = false;

        GridView2.DataSource = null;
        GridView2.DataBind();
        pnlVATResult.Visible = false;

        //ddlFiles.DataSource = null;
        //ddlFiles.DataBind();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.Clear();

        if (dtPostDateFrom.date.Length != 0 && dtPostDateTo.date.Length != 0)
        {
            if (ddlFiles.SelectedValue.Length == 0 || ddlFiles.SelectedValue == "" || ddlFiles.SelectedValue == "------ Files ------")
            {
                lblError.Text = "Please Select the File Name";
            }
            else
            {
                pnlResult.Visible = true;
                HyperLink1.Visible = false;
                pnlBR.Visible = false;
                ExceptionUtility.LogException(0, "", "5.132", "btnSearch_Click", ""); //channelID: " + channelID + ", eventID: " + eventID + ", pageSize: " + pageSize + ", pageNumber: " + pageNumber);

                loadResult(Helper.gridSize(), 1);
            }
        }
        else lblError.Text = "Please Enter the From & To Post Dates";
    }

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        //string channelID = "", EventID = "";
        //if (ddlChannels.SelectedIndex > 0)
        //    channelID = ddlChannels.SelectedValue;
        //if (ddlEvents.SelectedIndex > 0)
        //    EventID = ddlEvents.SelectedValue;
        //pnlBR.Visible = false;
        //ExceptionUtility.LogException(0, "", "", "ddlPages_SelectedIndexChanged", "");
        //loadResult(channelID, EventID, Helper.gridSize(), int.Parse(ddlPages.SelectedValue));
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("v"))
        {
            intCount = 0;
            ExceptionUtility.LogException(0, "", "5.8", "GridView1_RowCommand.Edit", "");
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GridView1.DataKeys[index].Value.ToString();
            pnlBR.Visible = true;
            pnlBR.Enabled = true;
            ViewState["rowid"] = rowID;
            ViewState["mode"] = "u";
            //addrow.Visible = false;
        }
        else if (e.CommandName.Equals("g"))
        {
            ExceptionUtility.LogException(0, "", "5.7", "GridView1_RowCommand.View", "");
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GridView1.DataKeys[index].Value.ToString();
            generateVATGL(ddlFiles.SelectedItem.Text);
        }
    }

    public string GetFPStatus(string date, string filename, string filenumber)
    {
        DataTable dtRes = new DataTable();
        try
        {
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);

            OracleCommand oraCom = new OracleCommand();
            oraCom.CommandText = "select * from gwfile_summary_log where record_date = '" + Helper.getDate(date) + "' and file_name = '" + filename + "' and file_number = '" + filenumber + "'";
            oraCom.Connection = oracon;
            OracleDataAdapter da = new OracleDataAdapter(oraCom);

            da.Fill(dtRes);
            if (dtRes.Rows.Count > 0)
            {
                return dtRes.Rows[0]["GENVAT_FILE_FLAG"] as string;
            }
            else return "FALSE";
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
            return "EXCEPTION";
        }
    }

    private void loadVATResult()
    {
        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 = "Generate_VAT_Invoice.GetVATGLFileSummary";

            oracom.Parameters.Add("P_FileDate", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_Resp_FileDate", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_FileNumber", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_output", OracleType.Cursor).Direction = ParameterDirection.Output;

            oracom.Parameters["P_FileDate"].Value = dtPostDateFrom.date;
            oracom.Parameters["P_Resp_FileDate"].Value = dtPostDateTo.date;
            oracom.Parameters["P_FileNumber"].Value = ddlFiles.SelectedValue;

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

            oracon.Close();

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

            if (ds.Tables[0].Rows.Count != 0)
            {
                lblVAT.Text = "true";
            }
        }
        catch (Exception ex)
        {
            //ExceptionUtility.LogException(ex, "BUSINESS_RULES_EDITOR.Get_Business_Rules", "132.1", "loadResult", parameters);
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");

            lblError.Text = ex.Message;
        }
    }

    private void generateVATGL(string FileName)
    {
        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 = "Generate_VAT_Invoice.Generate_GLVAT_FILE";

            oracom.Parameters.Add("P_Current_Uid", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("P_GWFile_Name", OracleType.VarChar).Direction = ParameterDirection.Input;

            oracom.Parameters.Add("P_VAT_Inv_FileName", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            oracom.Parameters.Add("P_Res", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

            oracom.Parameters.Add("P_VATInv_File", OracleType.Clob).Direction = ParameterDirection.Output;


            oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();
            oracom.Parameters["P_GWFile_Name"].Value = FileName;

            oracom.ExecuteNonQuery();
            
            string a = oracom.Parameters["P_Res"].Value.ToString();
            if (a == "Successful")
            {
                OracleLob myLob = (OracleLob)oracom.Parameters["P_VATInv_File"].Value;
                string content = (String)myLob.Value;

                string filename = oracom.Parameters["P_VAT_Inv_FileName"].Value.ToString();
                StreamWriter sw = new StreamWriter(Server.MapPath("..\\VATFiles\\" + filename));
                sw.Write(content);
                sw.Close();

                oracon.Close();
                HyperLink1.Text = filename;
                HyperLink1.NavigateUrl = "..\\VATFiles\\" + filename;
                HyperLink1.Visible = true;
                //lblError.Text = error;

                //this.loadVATResult();
                pnlVATResult.Visible = true;
            }
            else
            {
                lblError.Text = a;
                pnlVATResult.Visible = false;
            }
            oracon.Close();

            // Label2.Text += "1 ";

        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "gl_processor.Generate_BDC_GL", "", "GenerateBDCFile", "");

            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
        }
    }
   
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string fstatus = GetFPStatus(e.Row.Cells[0].Text, e.Row.Cells[3].Text, e.Row.Cells[4].Text);
            //if (e.Row.Cells[5].Text == "Response File Rejected" || e.Row.Cells[5].Text == "Error In Process")
            if(fstatus == "N")
            {
                (e.Row.FindControl("btn_Generate_VAT_File") as Button).Enabled = true;
            }
            else
            {
                (e.Row.FindControl("btn_Generate_VAT_File") as Button).Enabled = false;
            }
        }
    }

    protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("v"))
        {
            int index = int.Parse(e.CommandArgument.ToString());
            string rowID = GridView1.DataKeys[index].Value.ToString();
            string VATFileDate = Helper.getDate(GridView2.Rows[index].Cells[0].Text.ToString());
            string VATFileName = GridView2.Rows[index].Cells[3].Text.ToString();

            ScriptManager.RegisterClientScriptBlock(this, typeof(string), "new window", "window.open('VATGLSummary.aspx?VATFileDate=" + VATFileDate + "&VATFileName=" + VATFileName + "','Redirect')", true);
        }
    }

    protected void btnGetFiles_Click(object sender, EventArgs e)
    {
        this.Clear();
        loadFileNames();
        ExceptionUtility.LogException(0, "", "", "btnGetFiles_Click", "");//rowID: " + rowID);
    }
}
