using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO ;

namespace FHTE.LTOOLS.GUI
{
	/// <summary>
	/// In the RemoteBoxDialog you can specify a remote server to connect for LTools.
	/// </summary>
	public class RemoteBoxDialog : System.Windows.Forms.Form
	{
        #region Fields
        // ############################################################################################################
        // FIELDS
        // ############################################################################################################
        // private System.Windows.Forms.TextBox textBoxHostName;
        private System.Windows.Forms.ComboBox comboBoxHostName;
        private System.Windows.Forms.TextBox textBoxPortNumber;
        private System.Windows.Forms.Label labelHostName;
        private System.Windows.Forms.Label labelPortNumber;
        private System.Windows.Forms.Button buttonOk;
        private System.Windows.Forms.Button buttonCancel;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
        private ArrayList remoteHostsList = new ArrayList() ;   // ArrayList with hosts in hosts-file
        private MyDebug debugDialog ;                           // Dialog for debug-output
        private string hostsFile =                              // File with the saved hosts
            LTOOLSnet.GUIDirectory + "properties.ini" ;         //
        #endregion

        #region Properties
        // ############################################################################################################
        // PROPERTIES
        // ############################################################################################################
        /// <summary>
        /// get hostName Variable
        /// </summary>
        public string HostName
        {
            get { return comboBoxHostName.Text ; }
        }
        /// <summary>
        /// get portNumber Variable
        /// </summary>
        public int PortNumber
        {
            get { return Int32.Parse(this.textBoxPortNumber.Text) ; }
        }
		/// <summary>
		/// get the selected RemoteServer in the ComboBox
		/// </summary>
        public RemoteHost RemoteServer
        {
            get { return (RemoteHost)remoteHostsList[comboBoxHostName.SelectedIndex] ; }
        }
        #endregion


        #region Constructor
        // ############################################################################################################
        // CONSTRUCTORS
        // ############################################################################################################
        /// <summary>
        /// the Constructor show the dialog and sets the values in the textboxes.
        /// </summary>
        /// <param name="hostName">hostname to connect, e.g. "192.168.2.254" or "localhost"</param>
        /// <param name="portNumber">portnumber to connect to on server, e.g. "1605" (standard-port)</param>
        public RemoteBoxDialog(RemoteHost host) // string hostName, int portNumber)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            SetDebugDialog(LTOOLSnet.debugDialog) ;

            remoteHostsList.Add(host) ;
            GetHostsFromFile() ;
            UpdateComboBoxHostName() ;
            comboBoxHostName.SelectedIndex = 0 ;
        }
        #endregion


        #region Methods
        // ############################################################################################################
        // METHODS
        // ############################################################################################################
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

        /// <summary>
        /// The ButtonOk_Click() method checks if a new Host was inserted or the portNumber was changed.
        /// If a new Host was inserted in the comboBox, then the method adds a new RemoteHost to the 
        /// remoteHostsList. If just the portnumber was changed the method updates the current RemoteHost
        /// with the new PortNumber.
        /// </summary>
        /// <param name="sender">sender object</param>
        /// <param name="e">event data</param>
        private void ButtonOk_Click(object sender, System.EventArgs e)
        {
            int selectedIndex = comboBoxHostName.SelectedIndex ;
            if (selectedIndex == -1)
            {
                RemoteHost host = new RemoteHost(comboBoxHostName.Text, PortNumber) ;
                int index = remoteHostsList.Add(host) ;
                UpdateComboBoxHostName() ;
                comboBoxHostName.SelectedIndex = index ;
                ShowRemoteHostsList() ;
            }
            else if (PortNumber != ((RemoteHost)remoteHostsList[selectedIndex]).Port)
            {
                ((RemoteHost)remoteHostsList[selectedIndex]).Port = PortNumber ;
            }
        }

		#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()
		{
		    System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(RemoteBoxDialog));
		    this.labelHostName = new System.Windows.Forms.Label();
		    this.labelPortNumber = new System.Windows.Forms.Label();
		    this.textBoxPortNumber = new System.Windows.Forms.TextBox();
		    this.buttonOk = new System.Windows.Forms.Button();
		    this.buttonCancel = new System.Windows.Forms.Button();
		    this.comboBoxHostName = new System.Windows.Forms.ComboBox();
		    this.SuspendLayout();
		    // 
		    // labelHostName
		    // 
		    this.labelHostName.Location = new System.Drawing.Point(23, 20);
		    this.labelHostName.Name = "labelHostName";
		    this.labelHostName.Size = new System.Drawing.Size(102, 24);
		    this.labelHostName.TabIndex = 0;
		    this.labelHostName.Text = "Remote host:";
		    this.labelHostName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
		    // 
		    // labelPortNumber
		    // 
		    this.labelPortNumber.Location = new System.Drawing.Point(23, 59);
		    this.labelPortNumber.Name = "labelPortNumber";
		    this.labelPortNumber.Size = new System.Drawing.Size(102, 25);
		    this.labelPortNumber.TabIndex = 2;
		    this.labelPortNumber.Text = "Port number:";
		    this.labelPortNumber.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
		    // 
		    // textBoxPortNumber
		    // 
		    this.textBoxPortNumber.Location = new System.Drawing.Point(146, 59);
		    this.textBoxPortNumber.Name = "textBoxPortNumber";
		    this.textBoxPortNumber.Size = new System.Drawing.Size(205, 22);
		    this.textBoxPortNumber.TabIndex = 3;
		    this.textBoxPortNumber.Text = "port";
		    // 
		    // buttonOk
		    // 
		    this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK;
		    this.buttonOk.Location = new System.Drawing.Point(46, 99);
		    this.buttonOk.Name = "buttonOk";
		    this.buttonOk.Size = new System.Drawing.Size(128, 31);
		    this.buttonOk.TabIndex = 4;
		    this.buttonOk.Text = "OK";
		    this.buttonOk.Click += new System.EventHandler(this.ButtonOk_Click);
		    // 
		    // buttonCancel
		    // 
		    this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
		    this.buttonCancel.Location = new System.Drawing.Point(200, 99);
		    this.buttonCancel.Name = "buttonCancel";
		    this.buttonCancel.Size = new System.Drawing.Size(128, 31);
		    this.buttonCancel.TabIndex = 5;
		    this.buttonCancel.Text = "Cancel";
		    // 
		    // comboBoxHostName
		    // 
		    this.comboBoxHostName.Location = new System.Drawing.Point(146, 20);
		    this.comboBoxHostName.Name = "comboBoxHostName";
		    this.comboBoxHostName.Size = new System.Drawing.Size(205, 24);
		    this.comboBoxHostName.TabIndex = 6;
		    this.comboBoxHostName.Text = "remotehost";
		    this.comboBoxHostName.SelectedIndexChanged += new System.EventHandler(this.ComboBoxHostName_SelectedIndexChanged);
		    // 
		    // RemoteBoxDialog
		    // 
		    this.AcceptButton = this.buttonOk;
		    this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
		    this.CancelButton = this.buttonCancel;
		    this.ClientSize = new System.Drawing.Size(392, 152);
		    this.Controls.AddRange(new System.Windows.Forms.Control[] {
										  this.comboBoxHostName,
										  this.buttonCancel,
										  this.buttonOk,
										  this.textBoxPortNumber,
										  this.labelPortNumber,
										  this.labelHostName});
		    this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
		    this.MaximizeBox = false;
		    this.MaximumSize = new System.Drawing.Size(500, 300);
		    this.MinimizeBox = false;
		    this.MinimumSize = new System.Drawing.Size(300, 150);
		    this.Name = "RemoteBoxDialog";
		    this.ShowInTaskbar = false;
		    this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
		    this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
		    this.Text = "LTOOLS Connect to remote host";
		    this.ResumeLayout(false);

		}
		#endregion
        
        #region ComboBoxHostName Event-Handler
        /// <summary>
        /// the ComboBoxHostName_SelectedIndexChanged() sets the text in the textBoxPortNumber with the
        /// correct portNumber of the selected RemoteHost in the comboBox.
        /// </summary>
        /// <param name="sender">sender object</param>
        /// <param name="e">event data</param>
        private void ComboBoxHostName_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            int i = comboBoxHostName.SelectedIndex ;
            textBoxPortNumber.Text = ((RemoteHost)remoteHostsList[i]).Port.ToString() ;
        }
        /// <summary>
        /// The UpdateComboBoxHostName() fills the Combobox with the RemoteHosts in the remoteHostsList ArrayList.
        /// </summary>
        private void UpdateComboBoxHostName()
        {
            comboBoxHostName.Items.Clear() ;
            for (int i=0; i < remoteHostsList.Count; i++)
            {
                comboBoxHostName.Items.Add(((RemoteHost)remoteHostsList[i]).Host) ;
            }
        }
        #endregion

        #region GetHostsFromFile
        /// <summary>
        /// the GetHostsFromFile() method gets the Hosts from the "hostsFile" and inserts them
        /// in the remoteHostsList ArrayList.
        /// </summary>
        public void GetHostsFromFile()
        {
            if (!File.Exists(hostsFile))
            {
                return ;
            }
            FileStream fs = new FileStream(hostsFile, FileMode.Open, FileAccess.Read) ;
            StreamReader sr = new StreamReader(fs) ;
            string line ;
            while ((line = sr.ReadLine()) != null)
            {
                if (line.StartsWith("#") || line.StartsWith("["))
                {
                    continue ;
                }
                else if (line.Equals(""))
                {
                    continue ;
                }
                else
                {
                    try
                    {
                        int tab = line.IndexOf(" ") ;
                        string host = line.Substring(0, tab) ;
                        string port = line.Substring(tab + 1).Trim() ;
                        RemoteHost remoteHost = new RemoteHost(host, Int32.Parse(port)) ;
                        remoteHostsList.Add(remoteHost) ;
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message + "\n---" + line + "---") ;
                    }
                }
            }
            sr.Close() ;
            fs.Close() ;
        }
        #endregion

        #region MyDebug Dialog
        /// <summary>
        /// the SetDebugDialog() sets the reference to a MyDebug-dialog
        /// </summary>
        /// <param name="dDialog">a MyDebug-dialog</param>
        public void SetDebugDialog(MyDebug dDialog)
        {
            debugDialog = dDialog ;
        }

        /// <summary>
        /// the DebugOutput() method appends a string to the MyDebug-dialog.
        /// </summary>
        /// <param name="str">the string to append in MyDebug-dialog</param>
        void DebugOutput(string str)
        {
            if (debugDialog != null)
            {
                debugDialog.AppendText(str + "\r\n") ;
            }
        }
        #endregion

        #region Testmethods
        /// <summary>
        /// DebugOutput of the complete remoteHostsList ArrrayList.
        /// </summary>
        private void ShowRemoteHostsList()
        {
            DebugOutput("remoteHostsList:") ;
            for (int i=0; i < remoteHostsList.Count; i++)
            {
                DebugOutput(i + ": " + ((RemoteHost)remoteHostsList[i]).Host + " --- " + ((RemoteHost)remoteHostsList[i]).Port) ;
            }
        }

        /// <summary>
        /// The main entry point for the application to test the RemoteBoxDialog.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Form myForm = new Form () ;
            // Set the caption bar text of the form.   
            myForm.Text = "RemoteBoxDialog Test";
            myForm.Size = new Size (600, 400) ;
            myForm.Visible = true ;
            RemoteBoxDialog myDialog = new RemoteBoxDialog(new RemoteHost("localhost", 1605)) ;
            myDialog.ShowDialog() ; // Modaler Dialog
            MessageBox.Show("HostName: " + myDialog.HostName + "\n" +
                       "PortNumber: " + myDialog.PortNumber + "\n",
                       "RemoteBoxDialog") ;

            // Application.Run(new RemoteBoxDialog(null, "localhost", "1605"));
        }
        #endregion

        #endregion

	}
}
