using System;
using System.Data;
using System.Configuration;
using System.Linq;
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.Xml.Linq;
using System.Data.OracleClient;
using System.IO;
using System.Net.Sockets;
using System.Security.Permissions;
using System.Diagnostics;

/// <summary>
/// Summary description for SFTPSender
/// </summary>
public class SFTPSender
{
    private string _RemotePath;    
    private string _fileName;
    private string _SftpString;
    private string _LocalPath;
    private string _ProcessedPath;
    private string _iniFileName;

	public SFTPSender(string fileName)
	{
		//
		// TODO: Add constructor logic here
		//        
        _fileName = fileName;        
        _SftpString = SFTP_Details();
        _ProcessedPath = ConfigurationManager.AppSettings["ProcessedDir"].ToString();
        _iniFileName = ConfigurationManager.AppSettings["SFTPINIFileName"].ToString();
        
	}

    public string RemotePath
    {
        set
        {
            _RemotePath = getDBdir(value);
        }
    }

    public string FileName
    {
        set { _fileName = value; }
    }

    public string LocalPath
    {
        set { _LocalPath = value; }
    }

    private string SFTP_Details()
    {
        string userName = ConfigurationManager.AppSettings["SFTPUserName"].ToString();
        string server = ConfigurationManager.AppSettings["SFTPServer"].ToString();
        string hostKey = ConfigurationManager.AppSettings["SFTPHostKey"].ToString();
        string privateKey = ConfigurationManager.AppSettings["SFTPPrivateKey"].ToString();

        return "sftp://" + userName + "@" + server + " -hostkey=\\\"" + hostKey + "\\\"" + " -privatekey=" + privateKey + "";
    }
    
    private string getDBdir(string strParam)
    {
        string DBConnection = Helper.dbConnectionLive();

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

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;
        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "SYSTEM_PARAM_EDITOR.getRemoteDirForSFTP";

        oracom.Parameters.Add("p_current_uid", OracleType.Number).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_lang", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_Dir_Name", OracleType.VarChar, 250).Direction = ParameterDirection.Input;
        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["p_Dir_Name"].Value = strParam;
        oracom.Parameters["p_lang"].Value = "EN";
        oracom.Parameters["p_current_uid"].Value = "0";

        oracom.ExecuteNonQuery();
        oracon.Close();
        string SftpDirPath = oracom.Parameters["p_res_msg"].Value.ToString();
        return SftpDirPath;
    }

    private string WriteScript(string command1,string command2)
    {
        string scriptName = ConfigurationManager.AppSettings["SFTPLOG"].ToString() + "SFTP_" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt";
        StreamWriter script = File.CreateText(scriptName);            

        script.WriteLine("option batch abort");
        script.WriteLine("option confirm off");
        script.WriteLine("option transfer ascii");
        script.WriteLine("open " + _SftpString);        
        script.WriteLine(command1);
        script.WriteLine(command2);
        script.WriteLine("exit");

        script.Close();

        return scriptName;
    }

    public bool SftpUpload(ref string error)
    {
        string logFileName = ConfigurationManager.AppSettings["SFTPLOG"].ToString() + "SFTP_" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + ".log";        
        string scriptName = WriteScript("put -permissions=775 -nopreservetime  " + _fileName + " " + _RemotePath, ""); 

        try
        {            
            Process winscp = new Process();
            winscp.StartInfo.FileName = ConfigurationManager.AppSettings["SFTPFileName"].ToString();
            winscp.StartInfo.Arguments = "/ini=\"" + _iniFileName + "\"" + " /SCRIPT=\"" + scriptName + "\"" + " /LOG=\"" + logFileName + "\"";            
            winscp.StartInfo.UseShellExecute = false;
            winscp.StartInfo.RedirectStandardInput = true;
            winscp.StartInfo.RedirectStandardOutput = true;
            winscp.StartInfo.CreateNoWindow = true;
            winscp.Start();

            //winscp.StandardInput.WriteLine("option batch abort");
            //winscp.StandardInput.WriteLine("option confirm off");
            //winscp.StandardInput.WriteLine("option transfer ascii");
            //winscp.StandardInput.WriteLine("open " + _SftpString); /* saved session name*/
            //winscp.StandardInput.WriteLine("put -permissions=775 -nopreservetime  " + _fileName + " " + _RemotePath); /*local file adress*/
            //winscp.StandardInput.WriteLine("exit");
            //winscp.StandardInput.Close();

            do { }
            while (!winscp.HasExited);
         
            File.Delete(_fileName);

            return true;
        }

        catch (Exception ex)
        {
            error = "Msg:" + ex.Message + Environment.NewLine + "Inner Excepion:" + ex.InnerException +
                             Environment.NewLine + "Source :" + ex.Source;
            File.Delete(_fileName);
            return false;
        }        
    }

    public bool SftpDownload(ref string error)
    {
        string logFileName = ConfigurationManager.AppSettings["SFTPLOG"].ToString() + "SFTP_" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + ".log";
        string scriptName = WriteScript("get " + _RemotePath + _fileName + " " + _LocalPath + _fileName,
                                        "mv " + _RemotePath + _fileName + " " + _ProcessedPath + _fileName); 

        try
        {
            //get file from UNIX
            Process winscp = new Process();
            winscp.StartInfo.FileName = ConfigurationManager.AppSettings["SFTPFileName"].ToString();
            winscp.StartInfo.Arguments = "/ini=\"" + _iniFileName + "\"" + " /SCRIPT=\"" + scriptName + "\"" + " /LOG=\"" + logFileName + "\"";            
            winscp.StartInfo.UseShellExecute = false;
            winscp.StartInfo.RedirectStandardInput = true;
            winscp.StartInfo.RedirectStandardOutput = true;
            winscp.StartInfo.CreateNoWindow = true;
            winscp.Start();
            // Feed in the scripting commands
            //winscp.StandardInput.WriteLine("option batch abort");
            //winscp.StandardInput.WriteLine("option confirm off");
            //winscp.StandardInput.WriteLine("option transfer ascii");
            //winscp.StandardInput.WriteLine("open " + _SftpString); /* saved session name*/
            //winscp.StandardInput.WriteLine("Yes");
            //winscp.StandardInput.WriteLine("get " + _RemotePath + _fileName + " " + _LocalPath + _fileName); /*get the remote file to local dir*/
            //winscp.StandardInput.WriteLine("mv " + _RemotePath + _fileName + " " + _ProcessedPath + _fileName); /*move the remote file from remote path to Processed path*/
            //winscp.StandardInput.WriteLine("exit 0");
            //winscp.StandardInput.Close();

            do { }
            while (!winscp.HasExited);
        

            return true;
        }

        catch (Exception ex)
        {
            error = "Msg:" + ex.Message + Environment.NewLine + "Inner Excepion:" + ex.InnerException +
                             Environment.NewLine + "Source :" + ex.Source;            
            return false;
        }
    }

    

}
