using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Security.Cryptography;
using System.Net;

namespace Cheongbuk_MegaPark_Key_Management
{
    public class LicenseChecker
    {
        public bool CheckLicense()
        {
            string webDatas;
            using (WebClient webClient = new WebClient())
            {
                try
                {
                    webDatas = webClient.DownloadString("https://raw.githubusercontent.com/crudelis/CMPKM/main/license");
                }
                catch
                {
                    webDatas = "";
                }
            }
            string[] certifiedLicenses = webDatas.Split(new string[] { "\r\n", "\r", "\n" },    StringSplitOptions.None);
            certifiedLicenses = certifiedLicenses.Where(x => !string.IsNullOrEmpty(x)).ToArray();
            string localLicenseCode =  GetLocalLicense();
            foreach (var certified in certifiedLicenses)
            {
                if (certified == localLicenseCode)
                    return true;
            }
            return false;
        }
        private string GetLocalLicense()
        {
            string localBoardCode = GetBaseBoardCode();
            string md5LocalBoardCode = GetMD5(localBoardCode);
            System.IO.File.WriteAllText("license", md5LocalBoardCode);
            return md5LocalBoardCode;
        }
        private string GetBaseBoardCode()
        {
            string query = "SELECT * FROM Win32_BaseBoard";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            List<string> serialNumbers = new List<string>();
            foreach (var mObject in searcher.Get())
            {
                serialNumbers.Add(mObject.GetPropertyValue("SerialNumber").ToString());
            }
            return serialNumbers[0];
        }
        private string GetMD5(string data)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] input = Encoding.ASCII.GetBytes(data);
                byte[] hash = md5.ComputeHash(input);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hash.Length; i++)
                {
                    sb.Append(hash[i].ToString("X2"));
                }
                return sb.ToString();  
            }
        }
    }

    

}
