//  
//   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.IO;
using System.Windows.Forms;

using Rebex.Net;
using Rebex.TerminalEmulation;

namespace Rebex.Samples
{
    /// <summary>
    /// The main form of the application. It cantains the terminal control.
    /// </summary>
    public class MainForm : Form
    {
        /// <summary>
        /// Path to the config file at Local application data storage on the File system.
        /// </summary>
        private static readonly string _configFile = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), 
            string.Format("Rebex{0}TerminalEmulation{0}WinFormRExec.xml",Path.DirectorySeparatorChar));

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        private System.Windows.Forms.TextBox txtCommand;
        private System.Windows.Forms.Button btnSend;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txtResponse;
        private System.Windows.Forms.Label label2;

        /// <summary>
        /// The ssh object. It is used to comunicate with ssh server.
        /// </summary>
        private Ssh _ssh;

        /// <summary>
        /// Initialize this class.
        /// </summary>
        public MainForm()
        {
            InitializeComponent();

            CheckForIllegalCrossThreadCalls = true;
        }

        /// <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.txtCommand = new System.Windows.Forms.TextBox();
            this.btnSend = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.txtResponse = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // txtCommand
            // 
            this.txtCommand.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right)));
            this.txtCommand.Location = new System.Drawing.Point(88, 31);
            this.txtCommand.Name = "txtCommand";
            this.txtCommand.Size = new System.Drawing.Size(488, 20);
            this.txtCommand.TabIndex = 0;
            this.txtCommand.Text = "";
            this.txtCommand.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtCommand_KeyUp);
            // 
            // btnSend
            // 
            this.btnSend.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnSend.Location = new System.Drawing.Point(587, 31);
            this.btnSend.Name = "btnSend";
            this.btnSend.Size = new System.Drawing.Size(63, 23);
            this.btnSend.TabIndex = 1;
            this.btnSend.Text = "Send";
            this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(238)));
            this.label1.Location = new System.Drawing.Point(10, 34);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(67, 17);
            this.label1.TabIndex = 2;
            this.label1.Text = "Command:";
            // 
            // txtResponse
            // 
            this.txtResponse.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.txtResponse.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(238)));
            this.txtResponse.Location = new System.Drawing.Point(12, 60);
            this.txtResponse.Multiline = true;
            this.txtResponse.Name = "txtResponse";
            this.txtResponse.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.txtResponse.Size = new System.Drawing.Size(638, 494);
            this.txtResponse.TabIndex = 3;
            this.txtResponse.Text = "";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(238)));
            this.label2.Location = new System.Drawing.Point(10, 9);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(348, 17);
            this.label2.TabIndex = 4;
            this.label2.Text = "Note: Don\'t run commands that require user interaction.";
            // 
            // MainForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(659, 566);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.txtResponse);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.btnSend);
            this.Controls.Add(this.txtCommand);
            this.Name = "MainForm";
            this.Text = "Rebex Remote Exec";
            this.Load += new System.EventHandler(this.MainForm_Load);
            this.ResumeLayout(false);

        }

        #endregion

        /// <summary>
        /// Handles the form load event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                // show connection dialog
                Connection connection = new Connection(_configFile);

                // if not confirmed, exit the application
                if (connection.ShowDialog() != DialogResult.OK)
                {
                    Close();
                    return;
                }

                // create new Ssh object
                _ssh = new Ssh();

                // connect
                _ssh.Connect(connection.HostName);

                // login
                _ssh.Login(connection.UserName, connection.Password);
            }
            catch (Exception ex)
            {
                txtResponse.AppendText(string.Format("Exception occured: {0}", ex));
                txtCommand.Enabled = false;
                btnSend.Enabled = false;
            }
        }

        /// <summary>
        /// Handles the textbox 'Command' keyup event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCommand_KeyUp(object sender, KeyEventArgs e)
        {
            // when enter was pressed, send the commend
            if (e.KeyCode == Keys.Enter)
                SendCommand();
        }

        /// <summary>
        /// Handles the button 'Send' click event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            // when clicked on send, send the command
            SendCommand();
        }

        /// <summary>
        /// Sends the command to the remote host and writes the output.
        /// </summary>
        private void SendCommand()
        {
            string command = txtCommand.Text;

            if (command.Length == 0)
                return;

            try
            {
                // --------------------------------------------------------
                // This sample starts and runs a single command.
                // If you would like to run multiple commands in a single
                // shell session, use StartScripting() and refer to
                // http://www.rebex.net/terminal-emulation.net/features/scripting.aspx
                // --------------------------------------------------------

                // start a single command
                Scripting scripting = _ssh.StartScripting(command);

                // --------------------------------------------------------
                // A proper value of Scripting.Timeout property depends on the nature of
                // the command you invoke.
                // If the response of the command is being sent continuously,
                // the timeout can be small (for example commands like 'ls -R /').
                // If the response of the command is sent rarely or only at the end of the command,
                // bigger timeout should be used (for example commands like 'ls -R / > list.txt').
                // --------------------------------------------------------

                // set the timeout of the shell to 30 seconds
                scripting.Timeout = 30000;

                // read the response of the command
                string response = scripting.ReadUntil(ScriptEvent.Closed);

                // append the response
                if (response == null || response.Length == 0)
                {
                    txtResponse.AppendText("* No response.");
                }
                else
                {
                    txtResponse.AppendText(response.Replace("\n", "\r\n"));
                }
            }
            catch (Exception ex)
            {
                txtResponse.AppendText(string.Format("Exception occured: {0}", ex));
            }

            txtResponse.AppendText("\r\n");

            // scroll to the end of response
            txtResponse.SelectionStart = txtResponse.Text.Length;
            txtResponse.ScrollToCaret();

            // select the text of txtCommand to make it easier to enter a new command
            txtCommand.SelectAll();
        }
    }
}