//  
//   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.Text;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

using Rebex.TerminalEmulation;

namespace Rebex.Samples
{
    /// <summary>
    /// The main form of the application. It cantains the terminal control.
    /// </summary>
    public class MainForm : Form
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        private Rebex.TerminalEmulation.TerminalControl tcConsole;
        private System.Windows.Forms.FontDialog terminalFontDialog;
        private System.Windows.Forms.OpenFileDialog terminalOpenFileDialog;
        private System.Windows.Forms.ToolStripMenuItem menuItemFile;
        private System.Windows.Forms.ToolStripMenuItem menuItemOpen;
        private System.Windows.Forms.ToolStripMenuItem menuItemTools;
        private System.Windows.Forms.ToolStripMenuItem menuItemFont;
        private System.Windows.Forms.ToolStripMenuItem menuItemOptions;
        private StatusStrip statusStrip;
        private ToolStripStatusLabel statusLabel;
        private System.Windows.Forms.MenuStrip mmenu;
        private System.Windows.Forms.ToolStripMenuItem menuItemExit;
        private ToolStripMenuItem menuItemPlayer;
        private ToolStripMenuItem menuItemPauseUnpause;
        private ToolStripMenuItem menuItemSeektoNextFrame;
        private ToolStripMenuItem menuItemSpeedUp;
        private ToolStripMenuItem menuItemSlowDown;
        private ToolStripMenuItem menuItemClose;

        /// <summary>
        /// Player object. It simulates the ssh server.
        /// </summary>
        private AnsiPlayerShellChannel _player;

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

            CheckForIllegalCrossThreadCalls = true;

            // set the default encoding
            tcConsole.Options.Encoding = Encoding.UTF8;

            // set the size of the form to the size equal to 80 columns, 25 rows
            SetFormSize(80, 25);

            // register events
            tcConsole.RemoteResize += Console_RemoteResize;
            tcConsole.Disconnected += tcConsole_Disconnected;
        }

        /// <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.components = new System.ComponentModel.Container();
            this.tcConsole = new Rebex.TerminalEmulation.TerminalControl();
            this.terminalFontDialog = new System.Windows.Forms.FontDialog();
            this.terminalOpenFileDialog = new System.Windows.Forms.OpenFileDialog();
            this.mmenu = new System.Windows.Forms.MenuStrip();
            this.menuItemFile = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemOpen = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemExit = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemPlayer = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemPauseUnpause = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemSeektoNextFrame = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemSpeedUp = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemSlowDown = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemClose = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemTools = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemFont = new System.Windows.Forms.ToolStripMenuItem();
            this.menuItemOptions = new System.Windows.Forms.ToolStripMenuItem();
            this.statusStrip = new System.Windows.Forms.StatusStrip();
            this.statusLabel = new System.Windows.Forms.ToolStripStatusLabel();
            this.statusStrip.SuspendLayout();
            this.mmenu.SuspendLayout();
            this.SuspendLayout();
            // 
            // tcConsole
            // 
            this.tcConsole.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.tcConsole.BackColor = System.Drawing.Color.Magenta;
            this.tcConsole.Location = new System.Drawing.Point(0, 27);
            this.tcConsole.MousePasteEnabled = true;
            this.tcConsole.Name = "tcConsole";
            this.tcConsole.Recorder = null;
            this.tcConsole.ScrollbackResetOnDisplayActivity = true;
            this.tcConsole.ScrollBarEnabled = true;
            this.tcConsole.SelectionMode = Rebex.TerminalEmulation.TextSelectionMode.Standard;
            this.tcConsole.Size = new System.Drawing.Size(712, 400);
            this.tcConsole.TabIndex = 0;
            // 
            // terminalOpenFileDialog
            // 
            this.terminalOpenFileDialog.Filter = "ANSI files (*.ans;*.ansi)|*.ans;*.ansi|All files (*.*)|*.*";
            this.terminalOpenFileDialog.InitialDirectory = "..\\..\\SampleFiles";
            // 
            // mmenu
            // 
            this.mmenu.Items.AddRange(new System.Windows.Forms.ToolStripMenuItem[] {
            this.menuItemFile,
            this.menuItemPlayer,
            this.menuItemTools});
            this.mmenu.Location = new System.Drawing.Point(0, 0);
            this.mmenu.Size = new System.Drawing.Size(736, 24);
            this.mmenu.Name = "mmenu";
            this.mmenu.TabIndex = 3;
            // 
            // menuItemFile
            // 
            this.menuItemFile.MergeIndex = 0;
            this.menuItemFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripMenuItem[] {
            this.menuItemOpen,
            this.menuItemExit});
            this.menuItemFile.Text = "&File";
            // 
            // menuItemOpen
            // 
            this.menuItemOpen.MergeIndex = 0;
            this.menuItemOpen.Text = "&Open... (Ctrl+O)";
            this.menuItemOpen.Click += new System.EventHandler(this.menuItemOpen_Click);
            // 
            // menuItemExit
            // 
            this.menuItemExit.MergeIndex = 1;
            this.menuItemExit.Text = "E&xit (Alt+F4)";
            this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);
            // 
            // menuItemPlayer
            // 
            this.menuItemPlayer.MergeIndex = 1;
            this.menuItemPlayer.DropDownItems.AddRange(new System.Windows.Forms.ToolStripMenuItem[] {
            this.menuItemPauseUnpause,
            this.menuItemSeektoNextFrame,
            this.menuItemSpeedUp,
            this.menuItemSlowDown,
            this.menuItemClose});
            this.menuItemPlayer.Text = "&Player";
            // 
            // menuItemPauseUnpause
            // 
            this.menuItemPauseUnpause.MergeIndex = 0;
            this.menuItemPauseUnpause.Text = "&Pause / Unpause (Space)";
            this.menuItemPauseUnpause.Click += new System.EventHandler(this.menuItemPauseUnpause_Click);
            // 
            // menuItemSeektoNextFrame
            // 
            this.menuItemSeektoNextFrame.MergeIndex = 1;
            this.menuItemSeektoNextFrame.Text = "&Seek to next frame (N)";
            this.menuItemSeektoNextFrame.Click += new System.EventHandler(this.menuItemSeektoNextFrame_Click);
            // 
            // menuItemSpeedUp
            // 
            this.menuItemSpeedUp.MergeIndex = 2;
            this.menuItemSpeedUp.Text = "Speed &up 2x (Up arrow)";
            this.menuItemSpeedUp.Click += new System.EventHandler(this.menuItemSpeedUp_Click);
            // 
            // menuItemSlowDown
            // 
            this.menuItemSlowDown.MergeIndex = 3;
            this.menuItemSlowDown.Text = "Slow &down 2x (Down arrow)";
            this.menuItemSlowDown.Click += new System.EventHandler(this.menuItemSlowDown_Click);
            // 
            // menuItemClose
            // 
            this.menuItemClose.MergeIndex = 4;
            this.menuItemClose.Text = "&Close and Clear (Esc)";
            this.menuItemClose.Click += new System.EventHandler(this.menuItemClose_Click);
            // 
            // menuItemTools
            // 
            this.menuItemTools.MergeIndex = 2;
            this.menuItemTools.DropDownItems.AddRange(new System.Windows.Forms.ToolStripMenuItem[] {
            this.menuItemFont,
            this.menuItemOptions});
            this.menuItemTools.Text = "&Tools";
            // 
            // menuItemFont
            // 
            this.menuItemFont.MergeIndex = 0;
            this.menuItemFont.Text = "&Font...";
            this.menuItemFont.Click += new System.EventHandler(this.menuItemFont_Click);
            // 
            // menuItemOptions
            // 
            this.menuItemOptions.MergeIndex = 1;
            this.menuItemOptions.Text = "&Options...";
            this.menuItemOptions.Click += new System.EventHandler(this.menuItemOptions_Click);
            // 
            // statusStrip
            // 
            this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.statusLabel});
            this.statusStrip.Location = new System.Drawing.Point(0, 395);
            this.statusStrip.Name = "statusStrip";
            this.statusStrip.Size = new System.Drawing.Size(712, 22);
            this.statusStrip.TabIndex = 1;
            // 
            // statusLabel
            // 
            this.statusLabel.Name = "statusLabel";
            this.statusLabel.Size = new System.Drawing.Size(90, 21);
            this.statusLabel.Text = "Open a file first.";
            // 
            // MainForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(736, 425);
            this.Controls.Add(this.statusStrip);
            this.Controls.Add(this.tcConsole);
            this.Controls.Add(this.mmenu);
            this.KeyPreview = true;
            this.MainMenuStrip = this.mmenu;
            this.Name = "MainForm";
            this.Text = "Rebex ANSI Player";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_Closing);
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tcConsole_KeyDown);
            this.mmenu.ResumeLayout(false);
            this.mmenu.PerformLayout();
            this.statusStrip.ResumeLayout(false);
            this.statusStrip.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        /// <summary>
        /// Sets the correct form size with respect to all controls on it.
        /// </summary>
        /// <param name="columns">Number of columns of the console.</param>
        /// <param name="rows">Number of rows of the console.</param>
        private void SetFormSize(int columns, int rows)
        {
            // set the size of the form to the size of the console + height of the status bar
            Size newSize = tcConsole.GetControlSize(columns, rows);
            newSize.Height += statusStrip.Height;
            ClientSize = newSize;

            // console screen is not set immediately, set it manually right now
            tcConsole.SetScreenSize(columns, rows);
        }

        /// <summary>
        /// Handles the console RemoteResize event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Console_RemoteResize(object sender, RemoteResizeEventArgs e)
        {
            SetFormSize(e.Columns, e.Rows);
        }

        /// <summary>
        ///  Handles the console Disconnected event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tcConsole_Disconnected(object sender, EventArgs e)
        {
            // update the status bar
            statusLabel.Text = "Playing finished.";
        }

        /// <summary>
        /// Handles the 'Font' menu item click event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemFont_Click(object sender, System.EventArgs e)
        {
            // show the font dialog
            if (terminalFontDialog.ShowDialog() != DialogResult.OK)
                return;

            // check whether the selected font family is supported
            if(!TerminalFont.IsSupportedFamily(terminalFontDialog.Font.FontFamily))
            {
                MessageBox.Show(string.Format("Font {0} is not supported. Please choose another.", 
                    terminalFontDialog.Font.FontFamily.Name));
                return;
            }

            // set selected font to the console
            tcConsole.TerminalFont = new TerminalFont(terminalFontDialog.Font.FontFamily, terminalFontDialog.Font.Size);
        }

        /// <summary>
        /// Handles the terminal control keydown event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tcConsole_KeyDown(object sender, KeyEventArgs e)
        {
            // pause / unpause the player on space
            if (e.KeyCode == Keys.Space)
                PlayerPause();
            // seek to the next frame on 'N' or 'S'
            else if (e.KeyCode == Keys.N || e.KeyCode == Keys.S)
                PlayerSeekToNextFrame();
            // increase the speed on right arrow or up arrow
            else if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Up)
                PlayerSpeedUp();
            // decrease the speed on left arrow or down arrow
            else if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Down)
                PlayerSlowDown();
            // close the player and clear the screen on ESC
            else if (e.KeyCode == Keys.Escape)
                PlayerClose();
            // open file on CTRL+O
            else if (e.KeyCode == Keys.O && e.Modifiers == Keys.Control)
                Open();
            // application exit on ALT+F4
            else if (e.KeyCode == Keys.F4 && e.Modifiers == Keys.Alt)
                Exit();
        }

        /// <summary>
        /// Updates player status bar.
        /// </summary>
        private void UpdateStatus()
        {
            if (_player != null)
            {
                // update status bar
                if (_player.Connected)
                {
                    if (_player.IsPaused)
                        statusLabel.Text = "Paused...";
                    else
                        statusLabel.Text = "Playing...";

                    if (_player.Speed != 1)
                        statusLabel.Text += "   | Speed: " + _player.Speed.ToString();
                }
            }
        }

        /// <summary>
        /// Handles the form closing event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            // if the player is still connected, close it
            if (_player != null && _player.Connected)
                _player.Close();
        }

        /// <summary>
        /// Handles the 'Option' menu item click event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemOptions_Click(object sender, System.EventArgs e)
        {
            // show options dialog
            Options options = new Options(tcConsole.Options);
            options.ShowDialog();
        }

        /// <summary>
        /// Handles the 'Open' menu item click event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemOpen_Click(object sender, System.EventArgs e)
        {
            Open();
        }

        /// <summary>
        /// Handles the 'Exit' menu item click event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemExit_Click(object sender, System.EventArgs e)
        {
            Exit();
        }

        /// <summary>
        /// Event handler for menuItemPauseUnpause click'.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemPauseUnpause_Click(object sender, EventArgs e)
        {
            PlayerPause();
        }

        /// <summary>
        /// Event handler for menuItemSeektoNextFrame click.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemSeektoNextFrame_Click(object sender, EventArgs e)
        {
            PlayerSeekToNextFrame();
        }

        /// <summary>
        /// Event handler for menuItemSpeedUp click.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemSpeedUp_Click(object sender, EventArgs e)
        {
            PlayerSpeedUp();
        }

        /// <summary>
        /// Event handler for menuItemSlowDown click.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemSlowDown_Click(object sender, EventArgs e)
        {
            PlayerSlowDown();
        }

        /// <summary>
        /// Event handler for menuItemClose click.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemClose_Click(object sender, EventArgs e)
        {
            PlayerClose();
        }

        /// <summary>
        /// Asks for a file and starts the player.
        /// </summary>
        private void Open()
        {
            // open file dialog
            if (terminalOpenFileDialog.ShowDialog() != DialogResult.OK)
                return;

            // if the player was already created, close it and unbind it
            if (_player != null)
            {
                if (_player.Connected)
                    _player.Close();

                tcConsole.Unbind();

                // also clear screen
                tcConsole.Screen.Clear();
            }

            // create a new AnsiPlayerShellChannel based on the selected file
            _player = new AnsiPlayerShellChannel(terminalOpenFileDialog.OpenFile());

            // bind created AnsiPlayerShellChannel
            tcConsole.Bind(_player);

            // update the status bar
            statusLabel.Text = "Playing...";
        }

        /// <summary>
        /// Exits from the application.
        /// </summary>
        private void Exit()
        {
            // if the player was already created, close it and unbind it
            if (_player != null)
            {
                if (_player.Connected)
                    _player.Close();

                tcConsole.Unbind();
            }

            // close the form
            Close();
        }

        /// <summary>
        /// Pauses player.
        /// </summary>
        private void PlayerPause()
        {
            if (_player != null)
            {
                _player.IsPaused = !_player.IsPaused;

                UpdateStatus();
            }
        }

        /// <summary>
        /// Seeks player to next frame.
        /// </summary>
        private void PlayerSeekToNextFrame()
        {
            if (_player != null)
            {
                _player.SeekToNextFrame();

                UpdateStatus();
            }
        }

        /// <summary>
        /// Speeds up player.
        /// </summary>
        private void PlayerSpeedUp()
        {
            if (_player != null)
            {
                _player.Speed *= 2;

                UpdateStatus();
            }
        }

        /// <summary>
        /// Slows down player.
        /// </summary>
        private void PlayerSlowDown()
        {
            if (_player != null)
            {
                _player.Speed /= 2;

                UpdateStatus();
            }
        }

        /// <summary>
        /// Closes player.
        /// </summary>
        private void PlayerClose()
        {
            if (_player != null)
            {
                _player.Close();
                tcConsole.Screen.Clear(true);

                UpdateStatus();
            }
        }
    }
}