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;
using System.Security.Cryptography;
using System.Text;
using System.Threading;

public partial class CPS_MD5 : System.Web.UI.Page
{
    public bool GetMd5Hash(string strInFileName, string stroutFileName, bool bIgnoreLastChar)
    {

        try
        {
            MD5 md5Hash = MD5.Create();


            string strInput = System.IO.File.ReadAllText(strInFileName);


            if (bIgnoreLastChar && strInput[strInput.Length - 1] == '\n')
            {
                strInput = strInput.Substring(0, strInput.Length - 1);

            }

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(strInput));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            System.IO.File.WriteAllText(stroutFileName, sBuilder.ToString());
            // Return the hexadecimal string.
            return true;
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "", "36", "GetMd5Hash", "");
            return false;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadFiles();
            loadFiles2();
            links.Visible = false;
            ExceptionUtility.LogException(0, "", "36", "Page_Load", "");
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {

        var md5ExePath= ConfigurationSettings.AppSettings["MD5EXE"] as string;
        if ( md5ExePath== "Direct" || md5ExePath== "DirectExcludeLastLine")
        {
            bool bIgnoreLastChar = md5ExePath == "DirtExcludeLastLine" ? true : false;
            GenerateMD5(bIgnoreLastChar);
        }
    else
            GenerateMD5_WithEXE();
    }
    protected void GenerateMD5(bool bIgnoreLastChar )
    {
        try
        {

            string cps_p_dir, cps_iis;
            cps_p_dir = ConfigurationSettings.AppSettings["CPS_P"];
            cps_iis = ConfigurationSettings.AppSettings["CPS_P_IIS"];


            string inFileName_CPS = ddlFiles.SelectedValue;
            string outfilename_MD5 = ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5");

            if (!GetMd5Hash(cps_p_dir+"\\"+inFileName_CPS, cps_p_dir+"\\"+outfilename_MD5,false)) 
            {
                lblError.Text = "Failed to Generate MD5";
                return;
            }

            lblError.Text = "MD5 file generated successfully";

          
           
           bool loop = true;

            for (int i = 0; i < 5 && loop; i++)
            {
                try
                {
                    Thread.Sleep(5000);
                   
                        File.Move(ConfigurationSettings.AppSettings["CPS_P"] + "\\" + outfilename_MD5, ConfigurationSettings.AppSettings["CPS_P_IIS"] + "\\" + outfilename_MD5);
                    loop = false;       
                }
                catch (Exception ex)
                {
                    ExceptionUtility.LogException(ex, "", "36", "btnSearch_Click - Delay", outfilename_MD5);
                }
            }
             loop = true;
            for(int i=0;i<5&& loop;i++)  
            {
                try
                {
                    Thread.Sleep(5000);
                    File.Move(ConfigurationSettings.AppSettings["CPS_P"] + "\\" + inFileName_CPS,
                        ConfigurationSettings.AppSettings["CPS_P_IIS"] + "\\" + inFileName_CPS);
                    loop = false;      
                }
                catch (Exception exx)
                {
                    ExceptionUtility.LogException(exx, "", "36", "btnSearch_Click - Delay", inFileName_CPS);
                }
            }

        //    lnkCPS.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P_IIS_V"] + inFileName_CPS;
        //    lnkMD5.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P_IIS_V"] + outfilename_MD5;
            Session["CPS_File"] = inFileName_CPS;
            Session["MD5_File"] = outfilename_MD5;
           
            links.Visible = true;

            loadFiles();
            loadFiles2();
            ExceptionUtility.LogException(0, "", "", "btnSearch_Click", "");
        }
        catch (Exception ex)
        {
            lblError.Text = "File Not Generated. Error happened during the execution of the MD5 exe";
            ExceptionUtility.LogException(ex, "", "", "btnSearch_Click", "");
        }

    }

    protected void btnDownloadMD5_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogException(0, "", "", "btnDownloadMD5_Click", "Call:Start");
        string aFile = Session["MD5_File"] as string;

        if (!String.IsNullOrWhiteSpace(aFile))
        {
            ExceptionUtility.LogException(0, "", "", "btnDownloadMD5_Click", "Download file " + aFile);

            string FilePath = ConfigurationSettings.AppSettings["CPS_P_IIS_V"].ToString();
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + aFile);
            Response.TransmitFile(FilePath + aFile);
            Response.End();
        }
        else
            ExceptionUtility.LogException(0, "", "", "btnDownloadMD5_Click", "No File in Session to Download ");

        ExceptionUtility.LogException(0, "", "", "btnDownloadMD5_Click", "Call:End");
    }

    protected void btnDownloadCPS_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogException(0, "", "", "btnDownloadCPS_Click", "Call:Start");
        string aFile = Session["CPS_File"] as string;

        if (!String.IsNullOrWhiteSpace(aFile))
        {
            ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "Download file " + aFile);

            string FilePath = ConfigurationSettings.AppSettings["CPS_P_IIS_V"].ToString();
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + aFile);
            Response.TransmitFile(FilePath + aFile);
            Response.End();
        }
        else
            ExceptionUtility.LogException(0, "", "", "btnDownloadCPS_Click", "No File in Session to Download ");

        ExceptionUtility.LogException(0, "", "", "btnDownloadCPS_Click", "Call:End");
    }
    protected void GenerateMD5_WithEXE()
    {
        try
        {
            string md5_dir = ConfigurationSettings.AppSettings["MD5EXE"];
            System.Diagnostics.Process.Start(ConfigurationSettings.AppSettings["MD5EXE"],
                ddlFiles.SelectedValue);
            lblError.Text = "MD5 file generated successfully";

            bool finish = true;

            string filename, cps_p_dir, cps_iis;

            while (finish)
            {
                try
                {
                    filename = ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5");
                    cps_p_dir = ConfigurationSettings.AppSettings["CPS_P"];
                    cps_iis = ConfigurationSettings.AppSettings["CPS_P_IIS"];
                    File.Move(ConfigurationSettings.AppSettings["CPS_P"] + "\\" + ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5"),
                        ConfigurationSettings.AppSettings["CPS_P_IIS"] + "\\" + ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5"));
                    finish = false;
                }
                catch (Exception exx)
                {

                }
            }

            finish = true;
            while (finish)
            {
                try
                {

                    File.Move(ConfigurationSettings.AppSettings["CPS_P"] + "\\" + ddlFiles.SelectedValue,
                        ConfigurationSettings.AppSettings["CPS_P_IIS"] + "\\" + ddlFiles.SelectedValue);
                    finish = false;
                }
                catch (Exception exx)
                {

                }
            }

       //     lnkCPS.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P_IIS_V"] + ddlFiles.SelectedValue;
        //    lnkMD5.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P_IIS_V"] + ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5");
            Session["CPS_File"] = ddlFiles.SelectedValue;
            Session["MD5_File"] = ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5");

            links.Visible = true;

            loadFiles();
            loadFiles2();
            ExceptionUtility.LogException(0, "", "", "btnSearch_Click", "");
        }
        catch (Exception ex)
        {
            lblError.Text = "File Not Generated. Error happened during the execution of the MD5 exe";
            ExceptionUtility.LogException(ex, "", "", "btnSearch_Click", "");
        }

    }

    
    //protected void btnSearch_Click_old(object sender, EventArgs e)
    //{
    //    try
    //    {
    //        string md5_dir = ConfigurationSettings.AppSettings["MD5EXE"];
    //        System.Diagnostics.Process.Start(ConfigurationSettings.AppSettings["MD5EXE"], 
    //            ddlFiles.SelectedValue);
    //        lblError.Text = "MD5 file generated successfully";

    //        bool finish = true;

    //        string filename, cps_p_dir, cps_iis;

    //        while (finish)
    //        {
    //            try
    //            {
    //                filename = ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5");
    //                cps_p_dir = ConfigurationSettings.AppSettings["CPS_P"];
    //                cps_iis = ConfigurationSettings.AppSettings["CPS_P_IIS"];
    //                File.Move(ConfigurationSettings.AppSettings["CPS_P"] + "\\" + ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5"), 
    //                    ConfigurationSettings.AppSettings["CPS_P_IIS"] + "\\" + ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5"));
    //                finish = false;
    //            }
    //            catch (Exception exx)
    //            {

    //            }
    //        }

    //        finish = true;
    //        while (finish)
    //        {
    //            try
    //            {

    //                File.Move(ConfigurationSettings.AppSettings["CPS_P"] + "\\" + ddlFiles.SelectedValue, 
    //                    ConfigurationSettings.AppSettings["CPS_P_IIS"] + "\\" + ddlFiles.SelectedValue);
    //                finish = false;
    //            }
    //            catch (Exception exx)
    //            {

    //            }
    //        }

    //        lnkCPS.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P_IIS_V"] + ddlFiles.SelectedValue;
    //        lnkMD5.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P_IIS_V"] + ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5");
            
            
    //        //lnkCPS.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P"] + "\\" + ddlFiles.SelectedValue;
    //        //lnkMD5.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P"] + "\\" + ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5");
    //        links.Visible = true;

    //        loadFiles();
    //        loadFiles2();
    //        ExceptionUtility.LogException(0, "", "", "btnSearch_Click", "");
    //    }
    //    catch (Exception ex)
    //    {
    //        lblError.Text = "File Not Generated. Error happened during the execution of the MD5 exe";
    //        ExceptionUtility.LogException(ex, "", "", "btnSearch_Click", "");
    //    }

    //}

    private void loadFiles()
    {
        ddlFiles.Items.Clear();
        DirectoryInfo di = new DirectoryInfo(ConfigurationSettings.AppSettings["CPS_P"]);
        FileInfo[] rgFiles = di.GetFiles("*.CPS");
        foreach (FileInfo fi in rgFiles)
        {
            ddlFiles.Items.Add(fi.Name);
        }
    }

    private void loadFiles2()
    {
        ddlFiles2.Items.Clear();
        DirectoryInfo di = new DirectoryInfo(Server.MapPath("../CPS_FILES"));
        FileInfo[] rgFiles = di.GetFiles("*.CPS");
        foreach (FileInfo fi in rgFiles)
        {
            ddlFiles2.Items.Add(fi.Name);
        }
    }

    //protected void btnGenLink_Click(object sender, EventArgs e)
    //{
    //  lnk2.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P_IIS_V"] + ddlFiles2.SelectedValue;
        
    //}
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "Call:Start");
        

        if (ddlFiles2.Items.Count>=1)
        {
            string aFile = ddlFiles2.SelectedValue;
            ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "Download file " + aFile);

            string FilePath = ConfigurationSettings.AppSettings["CPS_P_IIS_V"].ToString();
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + aFile);
            Response.TransmitFile(FilePath + aFile);
            Response.End();
        }
        else
            ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "No File is selected to Download ");

        ExceptionUtility.LogException(0, "", "", "btnDownload_Click", "Call:End");
    }
}
