using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO.Ports;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Management;

namespace WindowsFormsApplication1
{
    static class PublicVarClass
    {

        public static string getPortAutomatic()
        {
            var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort");
            var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
            foreach (var v in ports)
            {

                if (v["caption"].ToString().ToLower().Contains("arduino"))
                {
                    return v["DeviceID"].ToString();
                }
            }
            return "";
        } 
        public static string CalculateMD5Hash(string input)

{

    // step 1, calculate MD5 hash from input

    System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();

    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);

    byte[] hash = md5.ComputeHash(inputBytes);


    // step 2, convert byte array to hex string

    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < hash.Length; i++)

    {

        sb.Append(hash[i].ToString("X2"));

    }

    return sb.ToString();

}



        public static void loadSetting()
        {
            try
            {
                var ofs = Registry.CurrentUser.OpenSubKey("Software\\Wow6432Node\\Sepahva", true);
                if (ofs == null)
                {
                    ofs = Registry.CurrentUser.CreateSubKey("Software\\Wow6432Node\\Sepahva");
                }


                var xofsRes = ofs.GetValue("xofs");
                var yofsRes = ofs.GetValue("yofs");
                var x0Res = ofs.GetValue("xO");
                var y0Res = ofs.GetValue("yO");
                var pRes = ofs.GetValue("port");
                var passRes = ofs.GetValue("data");
                var scaleRes = ofs.GetValue("scale");



                if (xofsRes == null)
                {
                    ofs.SetValue("xofs", xOffset.ToString());
                }
                else
                {
                    xOffset = Convert.ToInt32(xofsRes.ToString());
                }

                if (yofsRes == null)
                {
                    ofs.SetValue("yofs", yOffset.ToString());
                }
                else
                {
                    yOffset = Convert.ToInt32(yofsRes.ToString());
                }
                if (x0Res == null)
                {
                    ofs.SetValue("xO", x0.ToString());
                }
                else
                {
                    x0 = Convert.ToInt32(x0Res.ToString());
                }
                if (y0Res == null)
                {
                    ofs.SetValue("yO", y0.ToString());
                }
                else
                {
                    y0 = Convert.ToInt32(y0Res.ToString());
                }
                //if (pRes == null)
                //{
                //    ofs.SetValue("port", ports.ToString());
                //}
                //else
                //{
                //    if (pRes.ToString().Length > 1)
                //    {
                //        ports = pRes.ToString();
                //    }
                //    else
                //    {
                //        ports = getPortAutomatic();
                //    }
                    
                //}

                if (passRes == null)
                {
                    ofs.SetValue("data", pass.ToString());
                }
                else
                {
                    pass = passRes.ToString();
                }

                if (scaleRes == null)
                {
                    ofs.SetValue("scale", scale.ToString());
                }
                else
                {
                    scale = Convert.ToDouble(scaleRes.ToString());
                }
            }
            catch
            {
                MessageBox.Show("Cannot load data.");
            }

        }


        public static void savesettings()
        {
            try
            {
                var ofs = Registry.CurrentUser.OpenSubKey("Software\\Wow6432Node\\Sepahva", true);
                ofs.SetValue("xofs", xOffset.ToString());
                ofs.SetValue("yofs", yOffset.ToString());
                ofs.SetValue("xO", x0.ToString());
                ofs.SetValue("yO", y0.ToString());
                ofs.SetValue("port", ports.ToString());
                ofs.SetValue("scale", scale.ToString());
                
            }
            catch
            {
                
            }
            
        }

        public static void savePassword()
        {
            try
            {
                var ofs = Registry.CurrentUser.OpenSubKey("Software\\Wow6432Node\\Sepahva", true);
                ofs.SetValue("data", pass);
            }
            catch
            {
                MessageBox.Show("Cannot Save Password");
            }
        }

        static string convertToSTring(int x, int y, int a)
        {
            String res = "";
            if (x < 0)
            {
                res += "x=" + x.ToString("D3");
            }
            else
            {
                res += "x=+" + x.ToString("D3");
            }
            if (y < 0)
            {
                res += "y=" + y.ToString("D3");
            }
            else
            {
                res += "y=+" + y.ToString("D3");
            }
            if (a < 0)
            {
                res += "a=" + a.ToString("D3");
            }
            else
            {
                res += "a=+" + a.ToString("D3");
            }
            return res;
        }
        static byte[] convertToBytes(int[] ar)
        {
            byte[] bts = new byte[ar.Length * sizeof(int)];
            Buffer.BlockCopy(ar, 0, bts, 0, bts.Length);
            return bts;
        }
        static int[] decode(byte[] bts)
        {
            int[] arr = new int[bts.Length / sizeof(int)]; 
            Buffer.BlockCopy(bts, 0, arr, 0, bts.Length);

            return arr;
        }

        static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            Console.WriteLine(bytes.Length);
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }
        public static bool AutoChangePointSelected=true;// for automatic changing point to select in auto mode
        public static bool isAuto;
        public static bool InvalidPoints=false;
        public static int xCoef;
        public static int yCoef;
        //public static int aCoef;
        public static int x0 = 10;
        public static int y0 = 10;
        public static int x;
        public static int y;
        public static int a;
        public static int xOffset;
        public static int yOffset;
        //public static int aOffset;
        
        public static Point pointB;
        public static Point pointC;
        public static Point pointD;
        public static int numberOfPoints;//Should be removed
        public static bool pointBDetermined;
        public static bool pointCDetermined;
        public static bool pointDDetermined;
        public static string ports = getPortAutomatic();
        public static double scale = 1;
        public static string pass = CalculateMD5Hash(CalculateMD5Hash("123456"));
        /// <summary>
        /// Sends x,y,a
        /// </summary>
        public static void send()
        {
           
            try
            { 
                SerialPort port = new SerialPort(ports, 115200, Parity.None, 8, StopBits.One);
                if (!port.IsOpen)
                {
                    port.Open();  

                    string str = convertToSTring(x, y, a); 
                    byte[] bts = ASCIIEncoding.ASCII.GetBytes(str);
                    port.Write(bts, 0, bts.Length); 
                }
                if (port.IsOpen)
                {
                    port.Close();
                }
            }
            catch 
            {
                MessageBox.Show("Cannot Send data.");
            }
        }

    }
}
