using System;
using System.Collections.Generic;
using System.Text;
using everdrive3x.Misc;

namespace everdrive3x.Hardware
{
    class Device
    {


        DeviceControl control;
        DeviceProfile profile;
        static String port_cash;
 
        private Device()
        {
        }

        private Device(String port_name, bool boot_loader)
        {
            control = boot_loader ? DeviceControl.getBootLoaderControl(port_name) : DeviceControl.getDeviceControl(port_name);
            int device_id = boot_loader ? 0 : control.getDeviceID();
            int firmware = control.getFirmwareVersion();

            switch (device_id)
            {
                case DeviceList.ID_ED64R2:
                    profile = new ProfileED64R2(firmware);
                    break;
                case DeviceList.ID_ED32R2:
                    profile = new ProfileED32R2(firmware);
                    break;
                case DeviceList.ID_NUS_PROG:
                    profile = new ProfileNUS_PROG(firmware);
                    break;

                default:
                    profile = new ProfileDefault(firmware);
                    break;
            }

        }



        public DeviceControl Control
        {
            get { return control; }
        }

        public DeviceProfile Profile
        {
            get { return profile; }
        }


        public void close()
        {
            control.close();
        }

        public static Device searchDevice()
        {
            return search(false);
        }

        public static Device search(bool boot_loader)
        {
            String[] port_list = System.IO.Ports.SerialPort.GetPortNames();
            if(port_cash != null){
                try
                {
                    Hardware.Device d = new everdrive3x.Hardware.Device(port_cash, boot_loader);
                    return d;
                }
                catch (Exception) { }
            }
            

            foreach (String port in port_list)
            {
                try
                {
                    Hardware.Device d = new everdrive3x.Hardware.Device(port, boot_loader);
                    port_cash = port;
                    return d;
                }
                catch (Exception) { }
            }

            throw new Exception("device not detected");
        }

        public static Device searchBootLoader()
        {
            return search(true);
        }
    }
}
