//  
//   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.Windows.Forms;
using System.Xml;
using System.Collections.Generic;
using System.ComponentModel;

namespace Rebex.Samples
{
    public partial class ConnectionForm : Form
    {
        private readonly ConnectionFormData _data;

        public ConnectionFormData Data { get { return _data; } }

        public ConnectionForm() 
            : this(new ConnectionFormData(FileTransferComponent.FileTransfer))
        {
            if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
                throw new InvalidOperationException("Don't use the parameter-less constructor. It is intended for Visual Studio design mode only.");
        }

        public ConnectionForm(ConnectionFormData data)
        {
            if (data == null)
                throw new ArgumentNullException();

            _data = data;

            InitializeComponent();

            ucConnectionEditor.HideFtpGui = (_data.SupportedComponents & FileTransferComponent.Ftp) == 0;
            ucConnectionEditor.HideSftpGui = (_data.SupportedComponents & FileTransferComponent.Sftp) == 0;

            ucConnectionEditor.AdaptToCurrentVisibility();

            ConnectionEditorUtils.BindComboWithEnum<LogLevel>(cmbLogLevel, null);

            SetData();
        }

        /// <summary>
        /// Propagate current form fields values to the <see cref="Data"/> object.
        /// </summary>
        private void GetData()
        {
            ucConnectionEditor.GetData(_data);
            _data.LogLevel = (LogLevel)cmbLogLevel.SelectedValue;
        }

        /// <summary>
        /// Propagate current <see cref="Data"/> values to form fields.
        /// </summary>
        private void SetData()
        {
            ucConnectionEditor.SetData(_data);
            cmbLogLevel.SelectedValue = _data.LogLevel;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            List<string> errors = ucConnectionEditor.GetValidationErrors();
            if (errors.Count > 0)
            {
                string msg = string.Join("\r\n", errors.ToArray());
                ConnectionEditorUtils.ShowWarning(msg, "Invalid data");
                return;
            }

            if (!ucConnectionEditor.EnsurePrivateKey())
                return;
            if (!ucConnectionEditor.EnsureClientCertificate())
                return;

            DialogResult = DialogResult.OK;
            Close();
        }

        private void ConnectionForm_KeyPress(object sender, KeyPressEventArgs e)
        {
            // when 'esc' is pressed the form is closed
            if ((int)(e.KeyChar) == Convert.ToChar(Keys.Escape))
            {
                DialogResult = DialogResult.Cancel;
                Close();
            }
        }

        private void ConnectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // we gather values from form-fields to the Data object regarles the closing reason
            GetData();
        }

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.cmbLogLevel = new System.Windows.Forms.ComboBox();
            this.btnConnect = new System.Windows.Forms.Button();
            this.ucConnectionEditor = new Rebex.Samples.UcConnectionEditor();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(9, 355);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(73, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "Logging level:";
            // 
            // cmbLogLevel
            // 
            this.cmbLogLevel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.cmbLogLevel.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbLogLevel.FormattingEnabled = true;
            this.cmbLogLevel.Location = new System.Drawing.Point(119, 352);
            this.cmbLogLevel.Name = "cmbLogLevel";
            this.cmbLogLevel.Size = new System.Drawing.Size(121, 21);
            this.cmbLogLevel.TabIndex = 2;
            // 
            // btnConnect
            // 
            this.btnConnect.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.btnConnect.Location = new System.Drawing.Point(557, 350);
            this.btnConnect.Name = "btnConnect";
            this.btnConnect.Size = new System.Drawing.Size(75, 23);
            this.btnConnect.TabIndex = 3;
            this.btnConnect.Text = "Connect";
            this.btnConnect.UseVisualStyleBackColor = true;
            this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
            // 
            // ucConnectionEditor
            // 
            this.ucConnectionEditor.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.ucConnectionEditor.ClearCommandChannel = false;
            this.ucConnectionEditor.ClientCertificate = null;
            this.ucConnectionEditor.ClientCertificateFilename = null;
            this.ucConnectionEditor.FileTransferMode = Rebex.Net.FileTransferMode.Ftp;
            this.ucConnectionEditor.Location = new System.Drawing.Point(12, 12);
            this.ucConnectionEditor.MinimumSize = new System.Drawing.Size(620, 0);
            this.ucConnectionEditor.Name = "ucConnectionEditor";
            this.ucConnectionEditor.PassiveMode = false;
            this.ucConnectionEditor.PrivateKey = null;
            this.ucConnectionEditor.PrivateKeyFilename = "";
            this.ucConnectionEditor.Protocol = ((Rebex.Net.TlsVersion)((Rebex.Net.TlsVersion.TLS13 | Rebex.Net.TlsVersion.TLS12)));
            this.ucConnectionEditor.ProxyHost = "";
            this.ucConnectionEditor.ProxyPassword = "";
            this.ucConnectionEditor.ProxyPort = 0;
            this.ucConnectionEditor.ProxyType = Rebex.Samples.FileTransferProxyType.None;
            this.ucConnectionEditor.ProxyUser = "";
            this.ucConnectionEditor.ServerCertificateThumbprint = "";
            this.ucConnectionEditor.ServerCertificateVerifyingMode = Rebex.Samples.CertificateVerifyingMode.LocalyStoredThumbprint;
            this.ucConnectionEditor.ServerDomain = "";
            this.ucConnectionEditor.ServerHost = "";
            this.ucConnectionEditor.ServerKeyAlgorithm = Rebex.Net.SshHostKeyAlgorithm.RSA;
            this.ucConnectionEditor.ServerKeyFingerprint = "";
            this.ucConnectionEditor.ServerKeyHashAlgorithm = Rebex.Security.Certificates.SignatureHashAlgorithm.MD5;
            this.ucConnectionEditor.ServerKeyVerifyingMode = Rebex.Samples.KeyVerifyingMode.LocalyStoredFingerprint;
            this.ucConnectionEditor.ServerPassword = "";
            this.ucConnectionEditor.ServerPort = 0;
            this.ucConnectionEditor.ServerUser = "";
            this.ucConnectionEditor.Size = new System.Drawing.Size(620, 334);
            this.ucConnectionEditor.StorePassword = false;
            this.ucConnectionEditor.TabIndex = 0;
            this.ucConnectionEditor.UseGssApi = false;
            // 
            // ConnectionForm
            // 
            this.AcceptButton = this.btnConnect;
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(644, 382);
            this.Controls.Add(this.btnConnect);
            this.Controls.Add(this.cmbLogLevel);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.ucConnectionEditor);
            this.KeyPreview = true;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.MinimumSize = new System.Drawing.Size(660, 39);
            this.Name = "ConnectionForm";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Connection";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ConnectionForm_FormClosing);
            this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.ConnectionForm_KeyPress);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private UcConnectionEditor ucConnectionEditor;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.ComboBox cmbLogLevel;
        private System.Windows.Forms.Button btnConnect;
    }
}
