using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Redis;

namespace Siger.ApiCommon.Utilities
{
    public class License
    {
        private const string LicenseFileName = "License.license";
        public static List<ModuleStatus> ModuleStatuses;

        public static LicenseInformation CheckLicenseStatus(string key)
        {
            var infor = new LicenseInformation();
            var license = RedisCache.Instance.GetLicense(key);
            if (string.IsNullOrWhiteSpace(license))
            {
                infor.Status = LicenseStatus.NotFound;
                return infor;
            }
            return LicenseHelper.GetLicenseStatus(license);
        }

        public static void Register()
        {
            try
            {
                var licPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "License");
                if (!Directory.Exists(licPath))
                {
                    Directory.CreateDirectory(licPath);
                }
                var path = Path.Combine(licPath, LicenseFileName);
                if (File.Exists(path))
                {
                    var license = File.ReadAllText(path);
                    //RedisHelper.Instance.Set(LicenseKey, license);
                }
                else
                {
                    Logger.WriteLineError("license can not found.");
                }

                //watch license file
                Task.Run(() => WatchLicense(licPath, LicenseFileName));
            }
            catch (Exception e)
            {
                Logger.WriteLineError(e.Message);
            }
        }

        private static void WatchLicense(string path, string fileName)
        {
            var watcher = new FileSystemWatcher
            {
                Path = path,
                Filter = fileName
            };
            watcher.Changed += OnProcess;
            watcher.Created += OnProcess;
            watcher.Deleted += OnProcess;
            watcher.Renamed += OnProcess;
            watcher.EnableRaisingEvents = true;
            watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess
                                   | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
            watcher.IncludeSubdirectories = true;
        }

        private static void OnProcess(object source, FileSystemEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Created)
            {
                Read(e.FullPath);
            }
            else if (e.ChangeType == WatcherChangeTypes.Changed)
            {
                Read(e.FullPath);
            }
            else if (e.ChangeType == WatcherChangeTypes.Deleted || e.ChangeType == WatcherChangeTypes.Renamed)
            {
                //RedisHelper.Instance.Set(LicenseKey, string.Empty);
            }
        }

        private static void Read(string filePath)
        {
            using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                var sr = new StreamReader(fs, Encoding.Default);
                var license = new StringBuilder();
                while (!sr.EndOfStream)
                {
                    license.AppendLine(sr.ReadLine());
                }
                //RedisHelper.Instance.Set(LicenseKey, license.ToString());
            }
        }
    }
}
