using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
using HouseHeatingTerminal.Classes;

namespace HouseHeatingTerminal
{
    public partial class SettingsForm : Form
    {
        public SettingsForm()
        {
            InitializeComponent();
        }

        private bool settingsValid;

        private void SettingsForm_Load(object sender, EventArgs e)
        {
            terminalAddressMaskedTextBox.Text = Properties.Settings.Default.terminalAddress;
            localAddressMaskedTextBox.Text = Properties.Settings.Default.localAddress;
            autoConnectCheckBox.Checked = Properties.Settings.Default.autoConnect;
            PopulateInstalledSerialPortsCombo();
            terminalAddressMaskedTextBox.ValidatingType = typeof(HexValidator);
            localAddressMaskedTextBox.ValidatingType = typeof(HexValidator);
            refreshIntervalNumericUpDown.Value = Properties.Settings.Default.refreshInterval;
            timeoutNumericUpDown.Value = Properties.Settings.Default.timeoutInterval;
            timeUpdAtConnCheckBox.Checked = Properties.Settings.Default.updTimeAtConn;
            logFilePathTextBox.Text = Properties.Settings.Default.logPath;

            
        }

        private void PopulateInstalledSerialPortsCombo()
        {
            serialPortComboBox.Items.Clear();
            serialPortComboBox.Text = "";
            string[] ports = SerialPort.GetPortNames();
           
            if (ports.Length != 0)
            {
                foreach (string port in ports)
                {
                    serialPortComboBox.Items.Add(port);
                }
                if (Properties.Settings.Default.SerialPort == "")
                {
                    serialPortComboBox.SelectedIndex = 0;
                }
                else
                {
                    serialPortComboBox.Text = Properties.Settings.Default.SerialPort;
                }

                displaySerialPortSettings(true);
                PopulateSerialPortsBitsPerSecondCombo();
            }
            else
            {
                
                displaySerialPortSettings(false);
                // Add routine if any COM port exists.
            }
            
        }


        private void PopulateSerialPortsBitsPerSecondCombo()
        {
            serialPortBitsPerSecondComboBox.Items.Clear();
            string[] baudrates = { "300", "600", "1200", "1800", "2400", "4800", "7200", "9600", "14400", "19200", "38400", "57600", "115200", "230400", "460800", "921600" };
            foreach(string baudrate in baudrates)
            {
                serialPortBitsPerSecondComboBox.Items.Add(baudrate);
            }
            if (Properties.Settings.Default.BaudRate == "")
            {
                serialPortBitsPerSecondComboBox.SelectedItem = "14400";
            }
            else
            {
                serialPortBitsPerSecondComboBox.Text = Properties.Settings.Default.BaudRate;
                
            }

        }


        private void serialPortComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(serialPortComboBox.SelectedIndex != -1)
            {
               // HouseHeatingTerminal.Properties.Settings.Default.SerialPort = serialPortComboBox.Text;
            }
        }

        private void cancelBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void saveBtn_Click(object sender, EventArgs e)
        {
            settingsValid = true;
            localAddressMaskedTextBox.ValidateText();
            terminalAddressMaskedTextBox.ValidateText();
            if(!settingsValid)
            {
                this.DialogResult = DialogResult.None;
            }
            else
            {
                // save all settings
                HouseHeatingTerminal.Properties.Settings.Default.SerialPort = serialPortComboBox.Text;
                HouseHeatingTerminal.Properties.Settings.Default.BaudRate = serialPortBitsPerSecondComboBox.Text;
                HouseHeatingTerminal.Properties.Settings.Default.terminalAddress = terminalAddressMaskedTextBox.Text;
                HouseHeatingTerminal.Properties.Settings.Default.localAddress = localAddressMaskedTextBox.Text;
                HouseHeatingTerminal.Properties.Settings.Default.autoConnect = autoConnectCheckBox.Checked;
                HouseHeatingTerminal.Properties.Settings.Default.refreshInterval = Convert.ToUInt16(refreshIntervalNumericUpDown.Value);
                HouseHeatingTerminal.Properties.Settings.Default.timeoutInterval = Convert.ToUInt32(timeoutNumericUpDown.Value);
                HouseHeatingTerminal.Properties.Settings.Default.updTimeAtConn = timeUpdAtConnCheckBox.Checked;
                HouseHeatingTerminal.Properties.Settings.Default.logPath = logFilePathTextBox.Text;
                Properties.Settings.Default.Save();
                this.Close();
            }
            
          
        }

        private void serialPortComboBoxRefreshBtn_Click(object sender, EventArgs e)
        {
            PopulateInstalledSerialPortsCombo();
        }

        private void displaySerialPortSettings(bool enable)
        {
            serialPortComboBox.Enabled = enable;
            serialPortBitsPerSecondComboBox.Enabled = enable;

        }

        private void serialPortBitsPerSecondComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (serialPortBitsPerSecondComboBox.SelectedIndex != -1)
            {
               // HouseHeatingTerminal.Properties.Settings.Default.BaudRate = serialPortBitsPerSecondComboBox.Text;
            }
        }

        private void terminalAddressMaskedTextBox_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
        {
            terminalAddressMaskedTextBox.Text = terminalAddressMaskedTextBox.Text.ToUpper();
            terminalAddressMaskedTextBox.Text = terminalAddressMaskedTextBox.Text.Replace('X', 'x');
            
            if (e.IsValidInput)
            {
                settingsValid &= true;
                HideInvalidHEXToolTip();
                //AppendLog("Type validation succeeded.  Message: " + e.Message);        
            }
            else
            {
                settingsValid = false;
                ShowInvalidHEXToolTip(e.Message.Remove(0, (e.Message.IndexOf(':') + 1)), terminalAddressMaskedTextBox);
                
                //toolTip.Show(e.Message.Replace("System.ArgumentException: ", ""), this, terminalAddressMaskedTextBox.Location);
            }
        }

        private void ShowInvalidHEXToolTip(string message, Control control)
        {
            toolTip.ToolTipTitle = "Not valid input";
            toolTip.ToolTipIcon = ToolTipIcon.Warning;
            toolTip.SetToolTip(control,"qqq");
            toolTip.Show(message, control, 5000);
        }
        private void HideInvalidHEXToolTip()
        {
            toolTip.ToolTipTitle = "";
            toolTip.ToolTipIcon = ToolTipIcon.None;
            toolTip.Hide(this);
        }

        private void localAddressMaskedTextBox_TypeValidationCompleted(object sender, TypeValidationEventArgs e)
        {
            localAddressMaskedTextBox.Text = localAddressMaskedTextBox.Text.ToUpper();
            localAddressMaskedTextBox.Text = localAddressMaskedTextBox.Text.Replace('X', 'x');
            if (e.IsValidInput)
            {
                settingsValid &= true;
                HideInvalidHEXToolTip();
                //AppendLog("Type validation succeeded.  Message: " + e.Message);                
            }
            else
            {
                settingsValid = false;
                ShowInvalidHEXToolTip(e.Message.Remove(0, (e.Message.IndexOf(':') + 1)), localAddressMaskedTextBox);
                //toolTip.Show(e.Message.Replace("System.ArgumentException: ", ""), localAddressMaskedTextBox, localAddressMaskedTextBox.Location, 5000);
            }
        }

        private void logFileBrowse_Click(object sender, EventArgs e)
        {
            // logOpenFileDialog.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // use this when the database file is on the user's desktop
            logOpenFileDialog.ShowDialog();
        }

        private void logOpenFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            Properties.Settings.Default.logPath = logOpenFileDialog.FileName;
            logFilePathTextBox.Text = Properties.Settings.Default.logPath;
        }


    }
}
