//  
//   Rebex Sample Code License
// 
//   Copyright 2026, 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.IO;
using System.Threading;
using Rebex.IO;
using Rebex.Net;
using System.Threading.Tasks;

namespace Rebex.Samples
{
    /// <summary>
    /// This sample is a simple utility to upload/download a file to/from
    /// a FTP server using asynchronous methods of the Ftp class.
    /// </summary>
    class GetPutAsync
    {
        static void Main (string[] args)
        {
            // set the trial license key
            Rebex.Licensing.Key = Rebex.Samples.TrialKey.Key;


            string method = null;
            if (args.Length == 5)
            {
                switch (args[0].ToLower())
                {
                    case "get": method = "get"; break;
                    case "put": method = "put"; break;
                }
            }

            if (method == null)
            {
                // display syntax if wrong number of parameters or unsupported operation
                Console.WriteLine("FtpGetPutAsync - uploads or downloads a file from a FTP server");
                Console.WriteLine("Syntax: FtpGetPutAsync get|put none|explicit|implicit hostname remotepath localpath");
                Console.WriteLine("Example: FtpGetPutAsync get none test.rebex.net /pub/example/readme.txt readme.txt");
                return;
            }
            SslMode security = (SslMode)Enum.Parse(typeof(SslMode), args[1], true);
            string hostname = args[2];
            string remotePath = args[3];
            string localPath = args[4];

            // create Ftp object and set event handlers
            Ftp ftp = new Ftp();
            ftp.TransferProgressChanged += TransferProgressChanged;
            ftp.ResponseRead += ResponseRead;
            ftp.CommandSent += CommandSent;

            try
            {
                // set SSL to accept all server certificates...
                // do not do this in production code, server certificates should
                // be verified - use ftp.ValidatingCertificate event instead
                ftp.Settings.SslAcceptAllCertificates = true;

                // connect to the server
                ftp.Connect (hostname, security);
                // ask for username and password and login
                Console.Write ("Username: ");
                string username = Console.ReadLine();
                Console.Write ("Password: ");
                string password = Console.ReadLine();
                ftp.Login (username, password);
                Console.WriteLine ();

                // begin asynchronous transfer
                Task<long> operation;
                if (method == "get")
                    operation = ftp.GetFileAsync(remotePath, localPath);
                else
                    operation = ftp.PutFileAsync(localPath, remotePath);
                operation.ContinueWith(OperationCompleted);
                // do something else here...

                // wait for the transfer to end
                operation.Wait();

                if (operation.IsFaulted)
                {
                    foreach (Exception ex in operation.Exception.InnerExceptions)
                    {
                        if (ex is FtpException)
                            throw ex;
                    }

                    throw operation.Exception;
                }

                // get the result
                long bytes = operation.Result;
                // disconnect from the server
                ftp.Disconnect();
            }
            catch (FtpException e)
            {
                // output error description to the console
                Console.WriteLine ("'{0}' error: {1}", e.Status, e);
            }
            finally
            {
                // release all resources
                ftp.Dispose();
            }
        }

        public static void OperationCompleted(Task operation)
        {
            Console.WriteLine ("\nTransfer finished.");
        }


        public static void TransferProgressChanged (object sender, FtpTransferProgressChangedEventArgs e)
        {
            if (e.TransferState == TransferProgressState.DataBlockProcessed)
                Console.WriteLine ("\rTransferred {0} bytes...", e.BytesTransferred);
        }

        public static void ResponseRead (object sender, FtpResponseReadEventArgs e)
        {
            Console.WriteLine (e.Response);
        }

        public static void CommandSent (object sender, FtpCommandSentEventArgs e)
        {
            Console.WriteLine ("-> " + e.Command);
        }

    }
}
