//  
//   Rebex Sample Code License
// 
//   Copyright 2025, REBEX CR s.r.o.
//   All rights reserved.
//   https://www.rebex.net/
// 
//   Permission to use, copy, modify, and/or distribute this software for any
//   purpose with or without fee is hereby granted.
// 
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//   OTHER DEALINGS IN THE SOFTWARE.
// 

using System;
using System.Web.UI;
using Rebex.Samples.Code;
using Rebex.Net;

namespace Rebex.Samples
{
    public partial class Login : Page
    {
        /// <summary>
        /// Gets the return URL for redirect when connect was successful.
        /// </summary>
        private string ReturnUrl
        {
            get
            {
                if (!string.IsNullOrEmpty(Request[UrlParameter.ReturnUrl]))
                    return Request[UrlParameter.ReturnUrl];

                return string.Format("Default.aspx?{0}={1}", UrlParameter.Command, UrlParameterCommand.List);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                txtPort.Text = Sftp.DefaultPort.ToString();
            }

            // if LogOut command was specified
            if (Request[UrlParameter.Command] == UrlParameterCommand.LogOut)
                Logout();
        }

        /// <summary>
        /// Handles the 'Connect' button click.
        /// </summary>
        protected void Connect(object sender, EventArgs e)
        {
            CheckAndSaveConnectionInfo();
        }

        /// <summary>
        /// Checks entered connection values.
        /// If connection values are valid (it is possible to connect and log in to the remote server) saves them and 
        /// redirects to the URL specified in HttpRequest or the Default URL.
        /// </summary>
        private void CheckAndSaveConnectionInfo()
        {
            ConnectionInfo connectionInfo = new ConnectionInfo();

            // set connection info values
            connectionInfo.ServerName = txtServerName.Text;
            connectionInfo.Port = Convert.ToInt32(txtPort.Text);
            connectionInfo.UserName = txtUserName.Text;
            connectionInfo.Password = txtPassword.Text;


            // create new instance of a Sftp class
            Sftp sftp = new Sftp();

            try
            {
                // connect to the SFTP server
                sftp.Connect(connectionInfo.ServerName, connectionInfo.Port);

                // log in
                sftp.Login(connectionInfo.UserName, connectionInfo.Password);

                // disconnect from the SFTP server
                sftp.Disconnect();

                // connection was successful, save the connection information
                connectionInfo.Save();

                // redirect to the original URL
                Response.Redirect(ReturnUrl);
            }
            catch (SftpException ex)
            {
                // show error message
                lblError.Text = ex.Message;
            }
            finally
            {
                // dispose the Sftp object
                sftp.Dispose();
            }
        }

        /// <summary>
        /// Clears connection information.
        /// </summary>
        /// <remarks>
        /// In ASP.NET environment we have to perform ConnectToFtp - ExecuteCommnand - DisconnectFromFtp sequence on each request
        /// because SFTP connection will not survive between seaparate requests.
        /// </remarks>
        private void Logout()
        {
            // delete connection from session
            ConnectionInfo.Clear();
        }
    }
}