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 Business_AutomaticClaims : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadFiles();
            loadGCCFiles();
            pnlGCC.Visible = false;
            ExceptionUtility.LogException(0, "", "33", "Page_Load", "");
        }
    }

    protected void rdMADAClaims_CheckedChanged(object sender, EventArgs e)
    {
        pnlGCC.Visible = false;
        pnlBR.Visible = true;
        lblError.Text = "";
        ExceptionUtility.LogException(0, "", "", "rdMADAClaims_CheckedChanged", "");
    }

    protected void rdGCCClaims_CheckedChanged(object sender, EventArgs e)
    {
        pnlGCC.Visible = true;
        pnlBR.Visible = false;
        lblError.Text = "";
        ExceptionUtility.LogException(0, "", "", "rdGCCClaims_CheckedChanged", "");
    }

    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_dir_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();
            //ExceptionUtility.LogException("Success", "poslookup_getter.get_dir_files", "loadFiles", "");
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "poslookup_getter.get_dir_files","", "loadFiles", "");

        }
    }

    private void loadFiles1()
    {

        string DBConnection = Helper.dbConnection();

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

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

        DataSet ds = new DataSet();

        try
        {

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "poslookup_getter.get_dir_files";

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

            OracleDataAdapter da = new OracleDataAdapter(oracom);

            da.Fill(ds);
            ExceptionUtility.LogException(0, "poslookup_getter.get_dir_files", "", "loadFiles1", "");

        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("ORA-24338: statement handle not executed"))
            {

            }
            else
            {
                ExceptionUtility.LogException(ex, "poslookup_getter.get_dir_files", "", "loadFiles1", "");

            }
        }

        oracon.Close();
        //ddlFiles.DataSource = ds;
        //ddlFiles.DataBind();     
    }

    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_claim_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 generateGCC()
        {
            string DBConnection = Helper.dbConnection();

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

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

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "samaclaims.Generate_GCCNETClm_OutFile";

            oracom.Parameters.Add("p_Filepath", OracleType.VarChar).Direction = ParameterDirection.Input;
            oracom.Parameters.Add("p_file_name", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
            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.ExecuteNonQuery();
            oracon.Close();
            string respcode = oracom.Parameters["p_res_code"].Value.ToString();
            string resMsg   = oracom.Parameters["p_ResMsg"].Value.ToString();

            if (respcode == "0")
            {
                lblError.Text = resMsg; // "generating Completed";
            }
            else
                lblError.Text = resMsg; // "no claims are generated";
        }

        protected void btnGenerateGCC_Click(object sender, EventArgs e)
        {
            generateGCC();
        }
        private void loadGCCFiles()
        {
            ddlGCCFiles.Items.Clear();
            DirectoryInfo di = new DirectoryInfo(ConfigurationSettings.AppSettings["CPS_P"]);
            FileInfo[] rgFiles = di.GetFiles("GCC*.csv");
            foreach (FileInfo fi in rgFiles)
            {
                ddlGCCFiles.Items.Add(fi.Name);
            }
        }
    
        protected void btnGCCDownload_Click(object sender, EventArgs e)
        {
            ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "Call:Start");

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

                string FilePath = ConfigurationSettings.AppSettings["CPS_P"];       
                 
                 ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "The Selected File path name is  " + FilePath + aFile);

                 if (File.Exists(FilePath + aFile))
                   {
                       lblError.Text = "GCC Claim File is transmitted...";
                    Response.AppendHeader("Content-Disposition", "attachment; filename=" + aFile);
                    Response.TransmitFile(FilePath + aFile);
                   
                    ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "The Selected File is tranmistted! ");
                    ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "Call:End");
                    Response.End();
                   
                  }
                else
                {
                    lblError.Text = "The Selected File is not present in the Configured Download Path, Refer Configuration";
                    ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "The Selected File is not present in the COnfigured Download Path, Refer Configuration! ");
                }
            }
            else
                ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "No File is selected to Download ");
                ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "Call:End");
                lblError.Text = "No File is available to Download";
        }
    protected void btnLoad_Click(object sender, EventArgs e)
    {
        if (ddlFiles.Items.Count > 0)
            load();
        else
            lblError.Text = "There are no files";
    }

    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 = "samaclaims.loadsamaclaims";

        oracom.Parameters.Add("filepath", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("filename", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters["filepath"].Value = getDir();
        oracom.Parameters["filename"].Value = ddlFiles.SelectedValue;

        oracom.ExecuteNonQuery();
        oracon.Close();
        lblError.Text = "loading Completed";
    }

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

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

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

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "samaclaims.gensamaclaims";

        oracom.Parameters.Add("filepath", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_file_name", OracleType.VarChar,250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters["filepath"].Value = getDir();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();

        if (a == "0")
        {
            lblError.Text = "generating Completed";
            //string fileName = oracom.Parameters["p_file_name"].Value.ToString();
            //string downloadPath = ConfigurationSettings.AppSettings["DownloadDirectory"];
            //string downloadVirtualPath = ConfigurationSettings.AppSettings["DownloadVirtualDirectory"];
            //FileUtilityDLL.CPSFileReceiver cfr =
            //    new FileUtilityDLL.CPSFileReceiver(downloadPath, fileName);

            //lnkFile.NavigateUrl = downloadVirtualPath + fileName;
            //lnkFile.Text = "Download Generated File : " + fileName;
            //lnkFile.Visible = true;
        }
        else
            lblError.Text = "no claims are generated";
    }

    protected void btnGenerate_Click(object sender, EventArgs e)
    {
        generate();
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {

            string[] validFileTypes = { "cps" };//, "gif", "png", "jpg", "jpeg", "doc", "xls" };
            string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
            bool isValidFile = false;
            int count = FileUpload1.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.ForeColor = System.Drawing.Color.Red;
                lblError.Text = "Invalid File. Please upload a File with extension " +
                               string.Join(",", validFileTypes);

            }
            else
            {
                uploadFile();
            }
            
        }
        else
            lblError.Text = "Please choose a file";
    }

    private void uploadFile()
    {
        string uploadPath = ConfigurationSettings.AppSettings["CPS_D"];
        if (File.Exists(uploadPath + FileUpload1.FileName.Replace(" ", "")))
            lblError.Text = "file already exists";
        else
        {
            FileUpload1.SaveAs(uploadPath + FileUpload1.FileName.Replace(" ", ""));
            //FileUtilityDLL.CPSFileSender cfs =
            //    new FileUtilityDLL.CPSFileSender(uploadPath, FileUpload1.FileName.Replace(" ", ""));
            //loadFiles();
            lblError.Text = "CPS File Uploaded...";// and being transfered to the files list. Please wait for a few seconds and refresh the page";
        }
    }
}
