using Newtonsoft.Json;
using Syncfusion.Licensing;
using System;
using System.IO;

namespace SyncfusionSchedulerDeleteBug.Blazor.Server.Shared
{
    public static class SyncfusionLicenseActivator
    {
        private const string KeyFile = "SfLicense.json";

        public static void Activate()
        {
            LicenseInfo license = ReadLicense();

            if (license.HasKey == false)
                throw new LicenseException("License key cannot be empty");

            SyncfusionLicenseProvider.RegisterLicense(license.Key);
        }

        private static LicenseInfo ReadLicense()
        {
            try
            {
                string text = File.ReadAllText(KeyFile);
                return JsonConvert.DeserializeObject<LicenseInfo>(text);
            }
            catch (FileNotFoundException)
            {
                throw new LicenseException("Unable to access key");
            }
        }

        private class LicenseInfo
        {
            public string Key { get; set; }

            public bool HasKey => !string.IsNullOrEmpty(Key);
        }
    }

    public class LicenseException : Exception
    {
        public LicenseException(string message) : base(message) { }
    }
}
