using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO.Ports;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace WpfApplication19
{
    /// <summary>
    /// Interaction logic for Settings.xaml
    /// </summary>
    public partial class Settings : Window
    {
        SerialPort comport = new SerialPort(); 
		MainWindow _win;
		int _currentMachine;
        public Settings()
        {
            InitializeComponent();
        }

        private void init(object sender, RoutedEventArgs e)
        {
			_win = (MainWindow)Application.Current.MainWindow;
            //Console.WriteLine("hello");
            ComboBoxItem cb = new ComboBoxItem();
            cb.Tag = "None";
            cb.Content = "Select COM Port";
            //COMPorts.Items.Add(cb);
            Dictionary<string, string> friendlyPorts = Utils.BuildPortNameHash(SerialPort.GetPortNames());
            foreach (KeyValuePair<string, string> kvp in friendlyPorts)
            {
                //Console.WriteLine("Port '{0}' is better known as '{1}'", kvp.Key, kvp.Value);
                cb = new ComboBoxItem();
               
                cb.Tag = kvp.Key;
                cb.Content = "Port " + kvp.Key + " " + kvp.Value;
                COMPorts.Items.Add(cb);
            }
            foreach (ComboBoxItem item in COMPorts.Items)
            {
                if (item.Tag.ToString() == Utils.getSetting("machinePort"))
                {
                    COMPorts.SelectedItem = item;
                    //MessageBox.Show("help");
                }
            }

            
            //configDbCs.Text =  Utils.getSetting("configDbCS");
            //masterDbCs.Text =  Utils.getSetting("masterDbCS");
            //transDbCs.Text =  Utils.getSetting("tranDbCS");
            productionDbCS.Text = Utils.getSetting("productionDbCS");

			//webServerURL.Text = Utils.getSetting("webServerURL");
			/*
            var baudRateValue = Utils.getSetting("baudRate");
            var dataBitsValue = Utils.getSetting("dataBits");
            var stopBitsValue = Utils.getSetting("stopBits");
            var parityValue = Utils.getSetting("parity");*/
			_currentMachine = Convert.ToInt32(Utils.getSetting("currentMachine"));
			 
			/*
            setSelectBox(baudRateValue, baudRate);
            setSelectBox(dataBitsValue, dataBits);
            setSelectBox(stopBitsValue, stopBits);
            setSelectBox(parityValue, parity);
			 */
          //Console.ReadLine();

			
			initMachineList();
        }
		
		void initMachineList()
		{
			SqlDataReader reader = Utils.Query(_win.proConn, "select * from machines");
			while (reader.Read())
			{
				var id = Convert.ToInt32(reader["id"]);
				var cbi = new ComboBoxItem() { Tag = id, Content = reader["name"].ToString() };
				MachineCB.Items.Add(cbi); 
				if (id == _currentMachine)
				{
					MachineCB.SelectedItem = cbi;
				}
				
			
			}
			
			reader.Close();
		}
        private static void setSelectBox(string v, ComboBox cb)
        {
          foreach (ComboBoxItem item in cb.Items)
          {
            if (item.Content.ToString() == v)
            {
              cb.SelectedItem = item;
              //MessageBox.Show("help");
            }
          }
        }

        private void save_Click(object sender, RoutedEventArgs e)
        {
            ComboBoxItem cb = (ComboBoxItem)COMPorts.SelectedItem;
            
            if(cb != null){
                //debugText.Text = cb.Tag.ToString();
            
                Utils.UpdateSetting("machinePort",cb.Tag.ToString());
            }

            //Utils.UpdateSetting("configDbCS", configDbCs.Text);
            //Utils.UpdateSetting("masterDbCS", masterDbCs.Text);
            //Utils.UpdateSetting("tranDbCS", transDbCs.Text);
            Utils.UpdateSetting("productionDbCS", productionDbCS.Text);
            //Utils.UpdateSetting("baudRate", baudRate.Text);
            //Utils.UpdateSetting("dataBits", dataBits.Text);
            //Utils.UpdateSetting("stopBits", stopBits.Text);
            //Utils.UpdateSetting("parity", parity.Text);
			var cbi = MachineCB.SelectedItem as ComboBoxItem;
			Utils.UpdateSetting("currentMachine", cbi.Tag.ToString());
            //Utils.UpdateSetting("webServerURL", webServerURL.Text);
			this.Close();
		}

        private void testConnection_Click(object sender, RoutedEventArgs e)
        {
            connectDB();
           
        }

        private void connectDB()
        {
        }

        private void testConfig_Click(object sender, RoutedEventArgs e)
        {
          //testConnection(configDbCs.Text);
        }

        private void testConnection(string cs)
        {
          using (SqlConnection sqlConn = new SqlConnection())
          {
            try
            {
              sqlConn.ConnectionString = cs;
              sqlConn.Open();
              MessageBox.Show("Connectoin Success!!");
            }
            catch (SqlException se)
            {
              MessageBox.Show(se.Message);
            }
          }
        }
		

        private void portTest_Click(object sender, RoutedEventArgs e)
        {
          bool error = false;
          //comport.BaudRate = int.Parse(baudRate.Text);
          //comport.DataBits = int.Parse(dataBits.Text);
          //comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBits.Text);
          //comport.Parity;
          ComboBoxItem cbi = (ComboBoxItem)COMPorts.SelectedItem;
          comport.PortName = cbi.Tag.ToString();
          
          Console.WriteLine("br : {0}", comport.BaudRate);
          Console.WriteLine("dbit: {0}", comport.DataBits);
          Console.WriteLine("stb: {0}", comport.StopBits);
          Console.WriteLine("par: {0}", comport.Parity);

		  /*
          comport.BaudRate = int.Parse(baudRate.Text);
          comport.DataBits = int.Parse(dataBits.Text);
          comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBits.Text);
          comport.Parity = (Parity)Enum.Parse(typeof(Parity), parity.Text);
		  */
		  var w = (MainWindow)Application.Current.MainWindow;
		  if((w.comport.PortName == comport.PortName) && w.comport.IsOpen == true){
			MessageBox.Show("Open Port Success");
			return;
		  }
          try
          {
            comport.Open();
			MessageBox.Show("Open Port Success");
            comport.Close();
            
          }
          catch (UnauthorizedAccessException) { error = true; }
          catch (IOException) { error = true; }
          catch (ArgumentException) { error = true; }
          if (error)
          {
            MessageBox.Show("Open Port Fail");
          }
        }

        private void testPro_Click(object sender, RoutedEventArgs e)
        {
          testConnection(productionDbCS.Text);
        }

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

		

    }
} 
