using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace Narvaling.monitor.service
{
    internal class IdService
    {
        private static string id=null;
        private static string ObtenerCPUId()
        {
            string cpuInfo = String.Empty;
            try
            {

                System.Management.ManagementClass mgmt = new System.Management.ManagementClass("Win32_Processor");
                System.Management.ManagementObjectCollection objCol = mgmt.GetInstances();
                foreach (System.Management.ManagementObject obj in objCol)
                {
                    if (cpuInfo == String.Empty)
                    {
                        cpuInfo = obj.Properties["ProcessorId"].Value.ToString();
                    }
                }
                if (cpuInfo == String.Empty)
                    cpuInfo = "CPUID";


            }
            catch (Exception exp)
            {
                cpuInfo = "";
            }

            return cpuInfo.Trim();

        }
        private static string ObtenerMotherBoardID()
        {
            string serial = "MBID";
            try
            {
                ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
                ManagementObjectCollection moc = mos.Get();

                foreach (ManagementObject mo in moc)
                {
                    serial = (string)mo["SerialNumber"];
                }
            }
            catch (Exception exp)
            {
               
                serial = "";
            }

            return serial.Trim();
        }
        private static string MEI_CODE(int longitud)
        {
            string st = ObtenerCPUId() + ObtenerMotherBoardID();
            var resul = "";

            char[] code = new char[longitud];

            int minus = 'z'-'a'+1;
            int num = '9' - '0'+1;
            int mayus = 'Z' - 'A'+1;
            int maxi = minus + num + mayus;
            int pos = 0;
            foreach (char c in st)
            {
                code[pos] = (char)(code[pos] ^ c);
                pos=(pos+1) %longitud;
            }

            int e;
            foreach (char c in code)
            {
                e = c % maxi;
                if (e < minus)
                    resul = resul + (char)('a' + (e));
                else if (e < minus + mayus)
                    resul = resul + (char)('A' + (e - minus));
                else
                    resul = resul + (char)('0' + (e - minus - mayus));
            }

            return resul;

        }
        public static string GetMEI()
        {
            if (id == null)
                id = MEI_CODE(16);
            return id;
        }
    }
}
