//  
//   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 System.Web.UI.WebControls;
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 LogOut command was specified
            if (Request[UrlParameter.Command] == UrlParameterCommand.LogOut)
                Logout();

            if (!Page.IsPostBack)
            {
                txtPort.Text = Ftp.DefaultPort.ToString();
                // fill the Security DropDownList
                ddlSecurity.Items.Add(new ListItem("No security", Enum.GetName(typeof(SslMode), SslMode.None)));
                ddlSecurity.Items.Add(new ListItem("Explicit TLS or SSL", Enum.GetName(typeof(SslMode), SslMode.Explicit)));
                ddlSecurity.Items.Add(new ListItem("Implicit TLS or SSL", Enum.GetName(typeof(SslMode), SslMode.Implicit)));
                ddlSecurity.DataBind();
                trSecurity.Visible = true;
            }
        }

        /// <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;
            connectionInfo.Security = (SslMode)Enum.Parse(typeof(SslMode), ddlSecurity.SelectedValue, true);
            connectionInfo.AcceptAllCertificates = chkAcceptAllCertificates.Checked;

            // create new instance of a Ftp class
            Ftp ftp = new Ftp();

            try
            {
                ftp.Settings.SslAcceptAllCertificates = connectionInfo.AcceptAllCertificates;

                // connect to the FTP server
                ftp.Connect(connectionInfo.ServerName, connectionInfo.Port, connectionInfo.Security);

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

                // disconnect from the FTP server
                ftp.Disconnect();

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

                // redirect to the original URL
                Response.Redirect(ReturnUrl);
            }
            catch (FtpException ex)
            {
                // show error message
                lblError.Text = ex.Message;
            }
            catch (TlsException ex)
            {
                // show error message
                lblError.Text = ex.Message;
            }
            catch (Exception ex)
            {
                // show error message
                lblError.Text = ex.Message;
            }
            finally
            {
                // dispose the Ftp object
                ftp.Dispose();
            }
        }

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