using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
using System.Xml.Serialization;
using System.IO;




namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        logger log;
        devdata dev;
        Form_term f_term=null;

        // konstruktor formulare
        public Form1()
        {
            int i,iCntPorts;

            InitializeComponent();
            log = new logger(richTextBox1);
            dev = new devdata(log, tbAddress, tbTXDelay, tbRXDelay, tbRPTRDelay, tbTT, tbST, dataGridView1);

            // vytvoreni 200 radku
            dataGridView1.RowCount = 200;
            for (i = 0; i < 200; i++)
            {
                dataGridView1.Rows[i].Cells[0].Value = (i + 1).ToString();
            }

            // nacteni seznamu portu do CBPorts
            string[] lPorts = System.IO.Ports.SerialPort.GetPortNames();
            iCntPorts = lPorts.Length;
            if (iCntPorts>0)
            {
                foreach (string ss in lPorts)
                {
                    ToolStripMenuItem ti = cmx.DropDownItems.Add(ss) as ToolStripMenuItem;
                    ti.Click += new EventHandler(ti_Click);
                }
                (cmx.DropDownItems[0] as ToolStripMenuItem).Checked = true;                
                log.add(0, "Detected ports: " + String.Join(", ", lPorts));
            }
            else
            {
                log.add(1, "No serial port detected on this system.");
            }
        }

        // reakce po pri vyberu serioveho portu 
        void ti_Click(object sender, EventArgs e)
        {
            foreach(ToolStripItem si in cmx.DropDownItems)
            {
                ToolStripMenuItem mi = si as ToolStripMenuItem;
                mi.Checked = false;
            }
            (sender as ToolStripMenuItem).Checked = true;
        }

        // tlacitko na generovani nahodnych cisel do tabulky kodu
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            GenRandomCodes();
        }

        // vygeneruje nahodne kody do tabulky
        private void GenRandomCodes()
        {
            int i;
            Random r = new Random(Environment.TickCount);
            for (i = 0; i < 200; i++)
            {
                dataGridView1.Rows[i].Cells[1].Value = (r.Next(1, 9999)).ToString().PadLeft(4, '0');
            }
            log.add(0, "New random codes was successfully generated");
        }

        // obsluha tlacitka na generovani kodu
        private void generateRandomCodesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GenRandomCodes();
        }

        // vrati aktualne vybrany port
        private string getSelectedPort()
        {
            string sOut=null;
            foreach (ToolStripItem item in cmx.DropDownItems)
            {
                ToolStripMenuItem mi = item as ToolStripMenuItem;
                if (mi.Checked)
                {
                    sOut = mi.Text;
                    break;
                }
            }
            return sOut;
        }

        // fce Test Connections
        private void testConnectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            device d = new device(getSelectedPort(), log);
            d.IsPresent(true);
            d.close();
            d = null;
        }
      
        // fce Read Address
        private void tsbReadAddress_Click(object sender, EventArgs e)
        {
            device d = new device(getSelectedPort(), log);
            dev.ShowAddress(d.ReadAddr());
            d.close();
            d = null;
        }

        // fce Read Delays
        private void tsbReadDelays_Click(object sender, EventArgs e)
        {
            device d = new device(getSelectedPort(), log);
            dev.ShowDelays(d.ReadDelays());
            d.close();
            d = null;
        }

        // fce Read Codes
        private void tsbReadCodes_Click(object sender, EventArgs e)
        {
            device d = new device(getSelectedPort(), log);
            dev.ShowCodes(d.ReadCodes(progressBar1));
            d.close();
            d = null;
        }

        // fce Read All
        private void tsbReadAll_Click(object sender, EventArgs e)
        {
            device d = new device(getSelectedPort(), log);
            dev.ShowAddress(d.ReadAddr());
            dev.ShowDelays(d.ReadDelays());
            dev.ShowCodes(d.ReadCodes(progressBar1));
            d.close();
            d = null;
        }

        // fce Write Address
        private void tsbWriteAddress_Click(object sender, EventArgs e)
        {
            device d = new device(getSelectedPort(), log);
            d.WriteAddress(dev.GetAddress());
            d.close();
            d = null;
        }

        // fce Write Delays
        private void tsbWriteDelays_Click(object sender, EventArgs e)
        {
            device d = new device(getSelectedPort(), log);
            d.WriteDelays(dev.GetDelays());
            d.close();
            d = null;
        }

        // fce Write Codes
        private void tsbWriteCodes_Click(object sender, EventArgs e)
        {
            device d = new device(getSelectedPort(), log);
            d.WriteCodes(dev.GetCodes(),progressBar1);
            d.close();
            d = null;
        }

        // fce Write All
        private void tsbWriteAll_Click(object sender, EventArgs e)
        {
            device d = new device(getSelectedPort(), log);
            d.WriteAddress(dev.GetAddress());
            d.WriteDelays(dev.GetDelays());
            d.WriteCodes(dev.GetCodes(), progressBar1);
            d.close();
            d = null;
        }

        // fce Save config
        private void tsbSave_Click(object sender, EventArgs e)
        {
            int i;
            bool okflag = true;
            devstore devdmp = new devstore();
            devdmp.adresa = tbAddress.Text;
            devdmp.name = tbName.Text;
            devdmp.txdelay = tbTXDelay.Text;
            devdmp.rxdelay = tbRXDelay.Text;
            devdmp.rptrdelay = tbRPTRDelay.Text;
            devdmp.tonetime = tbTT.Text;
            devdmp.spacetime = tbST.Text;
            for (i = 0; i < 200; i++)
            {
                try
                {
                    devdmp.codes[i] = dataGridView1.Rows[i].Cells[1].Value.ToString();
                }
                catch
                {
                    devdmp.codes[i] = null;
                }
            }

            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Configuration files (*.cfg)|*.cfg|All files (*.*)|*.*";
            saveDialog.FilterIndex = 1;
            saveDialog.Title = "Save configuration";
            saveDialog.RestoreDirectory = true;
            try
            {
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    XmlSerializer s = new XmlSerializer(typeof(devstore));
                    Stream stream = File.Open(saveDialog.FileName, FileMode.Create);
                    s.Serialize(stream, devdmp);
                    stream.Close();
                    devdmp = null;
                }
            }
            catch
            {
                log.add(1, "Config save failed");
                okflag = false;
            }
            if (okflag) log.add(0, "Config saved to " + saveDialog.FileName); 
        }

        // fce Load config
        private void tsbLoad_Click(object sender, EventArgs e)
        {
            int i;
            bool okflag = true;
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "cfg files (*.cfg)|*.cfg|All files (*.*)|*.*";
            openDialog.FilterIndex = 1;
            openDialog.Multiselect = false;
            openDialog.Title = "Load configuration";
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    XmlSerializer s = new XmlSerializer(typeof(devstore));
                    Stream stream = File.Open(openDialog.FileName, FileMode.Open);
                    devstore devdmp = s.Deserialize(stream) as devstore;
                    stream.Close();
                    tbAddress.Text = devdmp.adresa;
                    tbName.Text = devdmp.name;
                    tbTXDelay.Text = devdmp.txdelay;
                    tbRXDelay.Text = devdmp.rxdelay;
                    tbRPTRDelay.Text = devdmp.rptrdelay;
                    tbTT.Text = devdmp.tonetime;
                    tbST.Text = devdmp.spacetime;
                    for (i = 0; i < 200; i++)
                    {
                        try
                        {
                            dataGridView1.Rows[i].Cells[1].Value = devdmp.codes[i];
                        }
                        catch
                        {
                            dataGridView1.Rows[i].Cells[1].Value = null;
                        }
                    }

                }
                catch
                {
                    log.add(1, "Config load failed");
                    okflag = false;
                }
                if (okflag) log.add(0, "Config load from " + openDialog.FileName);
            }
        }

        // fce Exit
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        // ovladani radiobuttonu pro vyber rezimu prikazu
        private void radioButtons_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonDirect.Checked)
            {
                tbCmdRepeater.Visible = false;
                tbCmdRemote.Visible = false;
                panelSipka.Visible = false;
                label6.Visible = false;
                label7.Visible = false;
                label8.Visible = true; 
                label9.Visible = true; 
                nudOut.Visible = true; 
                nudTime.Visible = true;
            }
            if (radioButtonRemote.Checked)
            {
                tbCmdRepeater.Visible = false;
                tbCmdRemote.Visible = true;
                panelSipka.Visible = true;
                label6.Visible = false;
                label7.Visible = true;
                label8.Visible = true; 
                label9.Visible = true; 
                nudOut.Visible = true; 
                nudTime.Visible = true;
            }
            if (radioButtonRepeater.Checked)
            {
                tbCmdRepeater.Visible = true;
                tbCmdRemote.Visible = true;
                panelSipka.Visible = true;
                label6.Visible = true;
                label7.Visible = true;
                label8.Visible = true; 
                label9.Visible = true; 
                nudOut.Visible = true; 
                nudTime.Visible = true;
            }
            if (radioButtonLiveTest.Checked)
            {
                tbCmdRepeater.Visible = false;
                tbCmdRemote.Visible = true;
                panelSipka.Visible = true;
                label6.Visible = false;
                label7.Visible = true;
                label8.Visible = false; 
                label9.Visible = false; 
                nudOut.Visible = false; 
                nudTime.Visible = false;
            }
        }

        // tlacitko Execute
        private void butExecute_Click(object sender, EventArgs e)
        {
            device d = new device(getSelectedPort(), log);
            if (!d.IsPresent(false)) return;
            tbCmdLocal.Text = d.ReadAddr();
            if (radioButtonDirect.Checked) d.ResetDirect((int) nudTime.Value, (int) nudOut.Value);
            if (radioButtonRemote.Checked) d.ResetRemote((int)nudTime.Value, (int)nudOut.Value, tbCmdRemote.Text);
            if (radioButtonRepeater.Checked) d.ResetRepeater((int)nudTime.Value, (int)nudOut.Value, tbCmdRemote.Text, tbCmdRepeater.Text);
            if (radioButtonLiveTest.Checked) d.LiveTest(tbCmdRemote.Text);
            d.close();
            d = null;
        }

        // tlacitko terminal
        private void terminalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (f_term == null)
            {
                f_term = new Form_term(getSelectedPort());
                try
                {
                    f_term.FormClosed += new FormClosedEventHandler(f_term_FormClosed);
                    f_term.Show();
                }
                catch {
                    f_term = null;
                }
            }
        }
        // akce po ukonceni okna terminalu
        void f_term_FormClosed(object sender, FormClosedEventArgs e)
        {
            f_term = null;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

        }

        






    }



    
}