using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;

namespace SFI.COMM.BASESYSTEM
{
    public static class LicenseController
    {
        private static ObservableCollection<string> ActiveKeyList = new ObservableCollection<string>();
        private static string FilePath { get; set; }

        public static void Start(string FilePath_)
        {
            using(StreamReader sr_ = new StreamReader(FilePath_))
            {
                string data_ = sr_.ReadToEnd();
                ActiveKeyList = new ObservableCollection<string>(JsonConvert.DeserializeObject<List<string>>(data_));
                if (ActiveKeyList == null)
                    ActiveKeyList = new ObservableCollection<string>();

                sr_.Close();
                sr_.Dispose();
            }
        }

        public static void CreateNewLicense(string ClientKey_)
        {
            if (ActiveKeyList.Any(t => t == ClientKey_))
                return;

            ActiveKeyList.Add(ClientKey_);
            SaveData();
        }

        public static void RemoveLicense(string ClientKey_)
        {
            if (!ActiveKeyList.Any(t => t == ClientKey_))
                return;

            ActiveKeyList.Remove(ClientKey_);
            SaveData();
        }

        public static bool CheckLicense(string ClientKey_) => ActiveKeyList.Any(t => t == ClientKey_);

        private static void SaveData()
        {
            using (StreamWriter sw_ = new StreamWriter(FilePath))
            {
                string data_ = JsonConvert.SerializeObject(ActiveKeyList);
                sw_.Write(data_);
                sw_.Flush();
                sw_.Close();
                sw_.Dispose();
            }
        }
    }
}
