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.IO;

public partial class POS_Merchant_Bulk_Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadFiles();
            loadGenFiles();
            ddlRespFiles.Visible = false;
           // pnlDwnload.Visible = false;
            pnlResult.Visible = false;
            btnViewResult.Visible = false;
            ExceptionUtility.LogException(0, "", "102", "Page_Load", "");
        }
    }
 
    private void loadFiles()
    {
        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 = "poslookup_getter.Get_MerchBulk_Reg_Files";

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

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

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

            oracon.Close();
            ddlFiles.Items.Insert(0, "------ Files to Load ------");

            ExceptionUtility.LogException(0, "poslookup_getter.Get_MerchBulk_Reg_Files", "102.1", "loadFiles", ", ");
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("ORA-24338: statement handle not executed"))
            {

            }
            else
            {
                ExceptionUtility.LogException(ex, "poslookup_getter.Get_MerchBulk_Reg_Files", "", "loadFiles", "");

            }
        }
    }

    private void loadGenFiles()
    {
        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 = "poslookup_getter.Get_Generated_merchbulk_files";

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

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

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

            oracon.Close();
            ddlGeneratedFiles.Items.Insert(0, "------ Generated Files ------");
            
            ExceptionUtility.LogException(0, "poslookup_getter.Get_Generated_merchbulk_files", "", "loadGenFiles", "");
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("ORA-24338: statement handle not executed"))
            {

            }
            else
            {
                ExceptionUtility.LogException(ex, "poslookup_getter.Get_MerchBulk_Reg_Files", "", "loadGenFiles", "");

            }
        }
    }
    protected void btnFileTransfer_Click(object sender, EventArgs e)
    {
        if (FileTransfer.HasFile)
        {
            string[] validFileTypes = { "csv" }; //    "xls" };
            string ext = System.IO.Path.GetExtension(FileTransfer.PostedFile.FileName);
            bool isValidFile = false;
            lblError.Text = "";
            int count = FileTransfer.FileName.Split('.').Length;
            if (count > 2)
            {
                lblError.Text = "Uploaded file has more than one extension. Please check the file and upload again";
                return;
            }
           
            for (int i = 0; i < validFileTypes.Length; i++)
            {
                if (ext == "." + validFileTypes[i])
                {
                    isValidFile = true;
                    
                    break;
                }
            }
            if (!isValidFile)
            {
                lblError.Text = "Invalid File Type ! Select only CSV File for File Transfer.";
            }
            else
            {
                transferFile();
            }
        }
        else
           
            lblError.Text = "Please choose a CSV file for File Transfer!";
    }

    private void transferFile()
    {
         
        string transferFilePath = ConfigurationSettings.AppSettings["CSV_F_IIS_V"];  // CSV_F_IIS_V CPS_D
        lblError.Text = "";

        if (File.Exists(transferFilePath + FileTransfer.FileName.Replace(" ", "")))
        {
            lblError.Text = "Selected " + FileTransfer.FileName + " file is already exists";
   
            ExceptionUtility.LogException(0, "btnFileTransfer_Click", "102.1", "transferFile", ", fileID: " + FileTransfer.FileName);
        }
        else
        {
            FileTransfer.SaveAs(transferFilePath + FileTransfer.FileName.Replace(" ", ""));
            lblError.ForeColor = System.Drawing.Color.Green;
            lblError.Text = FileTransfer.FileName + " - File is Transferred Successfully..";// and being transfered to the files list. Please wait for a few seconds and refresh the page";
            pnlDwnload.Visible = true;

            ExceptionUtility.LogException(0, "btnFileTransfer_Click", "102.1", "transferFile", ", fileID: " + FileTransfer.FileName);
        }
        // catch (Exception ex)
        //{
        //    ExceptionUtility.LogException(ex, "btnFileTransfer_Click", "102.1", "transferFile", ", Transfer File Path: " + transferFilePath);
            
        //    lblError.Text = transferFilePath. + " -  File Path is not configured to transfer the file. ";  
        //}
    }


   protected void btnLoad_Click(object sender, EventArgs e)
    {
        bool isValidFile = false;
        if (ddlFiles.Items.Count == 0)
        {
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Text = "There is no CSV file for file loading";
            isValidFile = true;
        }
        else
            if (isValidFile)
            {
                lblError.Text = "File Loading Error.";
            }
            else
            {
                if (ddlFiles.SelectedIndex == 0)
                {
                    lblError.Text = "Select the File to load";  
                }
                else
                {
                    load();
                    loadGenFiles();
                    ExceptionUtility.LogException(0, "", "2", "ddlFiles", ddlFiles.SelectedItem.Text);
                }
                
            }
           
    }

   private string getDir()
   {
       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 = "poslookup_getter.Get_MerchBulk_Reg_Dir";

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

           oracom.ExecuteNonQuery();
           oracon.Close();

           string a = oracom.Parameters["p_dir"].Value.ToString();
           return a;
       }
       catch (Exception ex)
       {
           ExceptionUtility.LogException(ex, "poslookup_getter.get_claim_dir", "", "getDir", "");
           return null;
       }
   }
    private void load()
    {
        string DBConnection = Helper.dbConnection();

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "Bulk_Merchant_Reg.Load_Merch_Reg_Job";

        oracom.Parameters.Add("P_FilePath", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("P_FileName", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_ResMsg", OracleType.VarChar, 500).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters["P_FilePath"].Value = getDir();
        oracom.Parameters["P_FileName"].Value = ddlFiles.SelectedValue;

        oracom.ExecuteNonQuery();
        oracon.Close();
       // lblError.Text = "Loading Completed";

        string respcode = oracom.Parameters["p_res_code"].Value.ToString();
        string resMsg = oracom.Parameters["p_ResMsg"].Value.ToString();

        if (respcode == "0")
        {
            lblError.ForeColor = System.Drawing.Color.Green;
            lblError.Text = ddlFiles.SelectedValue + " - File is loaded " + resMsg; // "Loading Completed";
        }
        else
        {
            lblError.Text = resMsg; // "Exception in File Loading";
        }
    }

    protected void ddlGeneratedFiles_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlGeneratedFiles.SelectedIndex  == 0)
        {


            ViewResult(ddlGeneratedFiles.SelectedValue);
            lblError.Text = "Select the File to download";
            pnlResult.Visible = false;
        }
        else
        {
            pnlResult.Visible = true;
            ViewResult(ddlGeneratedFiles.SelectedValue);
            ExceptionUtility.LogException(0, "", "2", "ddlGeneratedFiles_SelectedIndexChanged", ddlGeneratedFiles.SelectedItem.Text);
        }

    }
    protected void btnViewResult_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogException(0, "", "102.3", "btnViewResult_Click", "");
        
           if (ddlGeneratedFiles.SelectedIndex == 0)
            {   
                lblError.Text = "No Records found ! Select the File to view the result";
            }
            else
            {
                pnlResult.Visible = true;
                ViewResult(ddlGeneratedFiles.SelectedValue);
            }
    }

    private void ViewResult(string fileID)
    {
        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 = "FILE_LOADING_SUMMARY.Get_MerchBulkReg_Summary";
            
            oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_file_Name", 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_file_Name"].Value = fileID;
            oracom.Parameters["p_lang"].Value = "EN";
            oracom.Parameters["p_current_uid"].Value = Session["uid"].ToString();

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

            lblstime.Text = ds.Tables[0].Rows[0]["proc_start_time"].ToString();
            lblet.Text = ds.Tables[0].Rows[0]["proc_end_time"].ToString();
            lblstatus.Text = ds.Tables[0].Rows[0]["processing_status"].ToString();
            lblloaded.Text = ds.Tables[0].Rows[0]["records_loaded"].ToString();
            lblrejected.Text = ds.Tables[0].Rows[0]["records_rejected"].ToString();
            lbltotal.Text = ds.Tables[0].Rows[0]["total_records"].ToString();
            lblRecDate.Text = ds.Tables[0].Rows[0]["record_Date"].ToString();
            lblFileNumber.Text = ds.Tables[0].Rows[0]["file_number"].ToString();

            lblError.Text = "";
            ExceptionUtility.LogException(0, "FILE_LOADING_SUMMARY.Get_MerchBulkReg_Summary", "102.3", "ViewResult", ", fileID: " + fileID);
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "FILE_LOADING_SUMMARY.Get_MerchBulkReg_Summary", "102.3", "ViewResult", ", fileID: " + fileID);
            //Response.Redirect("../ErrorPages/ErrorPage.aspx");
            pnlResult.Visible = false;
            lblError.Text = ddlGeneratedFiles.SelectedValue + " -  No records found to view the result ";  
        }
    }

 

    protected void btnDownload_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "Call:Start");

        if (ddlGeneratedFiles.SelectedIndex == 0)
        {
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Text = "Select the File to Download";
        }
        else
        {

        if (ddlGeneratedFiles.Items.Count >= 1)
        {
            string aFile = ddlGeneratedFiles.SelectedValue;
            ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "Downloaded File Name: " + aFile);

            string FilePath = ConfigurationSettings.AppSettings["CSV_F_IIS_V"];  //  CPS_D

            ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "The Selected File path name is  " + FilePath + aFile);

            if (File.Exists(FilePath + aFile))
            {
                lblError.Text = "Selected File is transmitted...";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + aFile);
                Response.TransmitFile(FilePath + aFile);

                ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "The Selected File is downloaded! ");
                ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "Call:End");
                Response.End();

            }
            else
            {
                lblError.ForeColor = System.Drawing.Color.Red;
                lblError.Text = "The Selected File is not present in the folder";
                ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "The Selected File is not present in the COnfigured Download Path, Refer Configuration! ");
            }
        }
        else
        {
            ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "No File is selected to Download ");
            ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "Call:End");
            lblError.ForeColor = System.Drawing.Color.Red;
            lblError.Text = "No File is available to Download";
        }
      }
    }  

}
