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.Configuration;
using System.IO;

public partial class POS_AutomaticMonthlyClaims : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadFiles();
            ExceptionUtility.LogException(0, "", "86", "Page_Load", "");
        }
        btnLoadAdj.Enabled = false;
    }
    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_monthly_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_monthly_files", "", "loadFiles", "");

        }
    }
    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_monthly";

            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;
        }
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    { // IRFAN_MOD 170101

        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";

    //    if (FileUpload1.HasFile)
    //    {

    //        uploadFile();

    //    }
    //    else
    //        lblError.Text = "Please choose a file";
    //
    }
    private void uploadFile()
    {
        //DirectoryInfo di = new DirectoryInfo(Server.MapPath("../CPS_FILES"));
        string uploadPath = ConfigurationSettings.AppSettings["SAMA_MON"];
        if (!Directory.Exists(uploadPath))
        {
            DirectoryInfo di = Directory.CreateDirectory(uploadPath );
        }
        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 = "Monthly SAMA File Uploaded...";// and being transfered to the files list. Please wait for a few seconds and refresh the page";
        }
    }
    protected void btnLoad_Click(object sender, EventArgs e)
    {
       
        if (ddlFiles.Items.Count > 0)
        {
            if (ddlFiles.SelectedItem.Text.Contains("sama_close"))
            {
                if (loadCloseClaims(ddlFiles.SelectedItem.Text).Equals(1))
                {
                    lblError.Text = "File is loaded";
                    btnLoadAdj.Enabled = true;
                    ExceptionUtility.LogException(0, "", "", "btnLoad_Click", "");
                }
                else
                {
                    //btnLoadAdj.Enabled = true;
                    lblError.Text = "Error Loading close File. Please check the error log";
                    ExceptionUtility.LogException(9, "", "", "btnLoad_Click", "Check DB log " + ddlFiles.SelectedItem.Text + "_LOG.TXT");
                }
                //foreach (ListItem ltItem in ddlFiles.Items)
                //{
                //    if (ltItem.Value.Contains("sama_close"))
                //        if (loadCloseClaims(ltItem.Value).Equals(1))
                //        {
                //            ExceptionUtility.LogException(0, "", "", "btnLoad_Click", "");
                //        }
                //        else
                //        {
                //            lblError.Text = "Error Loading close File. Please check the error log";
                //            ExceptionUtility.LogException(9, "", "", "btnLoad_Click", "Check DB log " + ltItem.Value + "_LOG.TXT");
                //            return;
                //        }
                    //else if (ltItem.Value.Contains("sama_adj"))
                    //    if (loadAdjClaims(ltItem.Value).Equals(1))
                    //    {
                    //        ExceptionUtility.LogException(0, "", "", "btnLoad_Click", "");

                    //    }
                    //    else
                    //    {
                    //        lblError.Text = "Error Loading adj File. Please check the error log";
                    //        ExceptionUtility.LogException(9, "", "", "btnLoad_Click", "Check DB log " + ltItem.Value + "_LOG.TXT");
                    //        return;
                    //    }
                //}
                //lblError.Text = "File loaded";
            }
            else if (ddlFiles.SelectedItem.Text.Contains("sama_adj"))
            {
                if (loadAdjClaims(ddlFiles.SelectedItem.Text).Equals(1))
                {
                    lblError.Text = "File is loaded";
                    ExceptionUtility.LogException(0, "", "", "btnLoad_Click", "");
                }
                else
                {
                    lblError.Text = "Error Loading close File. Please check the error log";
                    ExceptionUtility.LogException(9, "", "", "btnLoad_Click", "Check DB log " + ddlFiles.SelectedItem.Text + "_LOG.TXT");
                }
            }
            //else
            //    lblError.Text = "Please select close file";
        }
        else
            lblError.Text = "There are no files";
    }
    private int loadCloseClaims(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 = "sama_monthly_claims.load_close_claims";

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

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


            oracom.Parameters["filename"].Value = fileName;

            oracom.ExecuteNonQuery();
            oracon.Close();
            //lblError.Text = "loading Completed";
            //return true;
            int res = int.Parse(oracom.Parameters["p_result"].Value.ToString());
            return res;
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "sama_monthly_claims.load_close_claims", "500.1", "loadCloseClaims", "filepath-" + getDir() + ":filename-" + fileName);
            return -1;
        }
    }
    private int loadAdjClaims(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 = "sama_monthly_claims.load_adj_claims";

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

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

            oracom.Parameters["filename"].Value = fileName;

            oracom.ExecuteNonQuery();
            oracon.Close();
            int res = int.Parse(oracom.Parameters["p_result"].Value.ToString());
            return res;
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "sama_monthly_claims.load_adj_claims", "500.2", "loadAdjClaims", "filepath-" + getDir() + ":filename-" + fileName);
            return -1;
        }
    }

    protected void btnLoadAdj_Click(object sender, EventArgs e)
    {
        if (ddlFiles.Items.Count > 0)
        {
            if (ddlFiles.SelectedItem.Text.Contains("sama_adj"))
            {
                if (loadAdjClaims(ddlFiles.SelectedItem.Text).Equals(1))
                {
                    lblError.Text = "File is loaded";
                    ExceptionUtility.LogException(0, "", "", "btnLoad_Click", "");
                }
                else
                {
                    lblError.Text = "Error Loading close File. Please check the error log";
                    ExceptionUtility.LogException(9, "", "", "btnLoad_Click", "Check DB log " + ddlFiles.SelectedItem.Text + "_LOG.TXT");
                }
                //foreach (ListItem ltItem in ddlFiles.Items)
                //{
                //    if (ltItem.Value.Contains("sama_close"))
                //        if (loadCloseClaims(ltItem.Value).Equals(1)) 
                //        {
                //            ExceptionUtility.LogException(0, "", "", "btnLoad_Click", "");
                //        }
                //        else
                //        {
                //            lblError.Text = "Error Loading close File. Please check the error log";
                //            ExceptionUtility.LogException(9, "", "", "btnLoad_Click", "Check DB log "+ltItem.Value +"_LOG.TXT");
                //            return;
                //        }
                //    else if (ltItem.Value.Contains("sama_adj"))
                //        if (loadAdjClaims(ltItem.Value).Equals(1))
                //        {
                //            ExceptionUtility.LogException(0, "", "", "btnLoad_Click", "");

                //        }
                //        else
                //        {
                //            lblError.Text = "Error Loading adj File. Please check the error log";
                //            ExceptionUtility.LogException(9, "", "", "btnLoad_Click", "Check DB log " + ltItem.Value + "_LOG.TXT");
                //            return;
                //        }
                //}
                //lblError.Text = "File loaded";
            }
            else
                lblError.Text = "Please select adjustment file";
        }
        else
            lblError.Text = "There are no files";
    }
}