using System;
using System.IO;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Logging;
using AyaNova.Util;
using AyaNova.Models;


namespace AyaNova.Biz
{

    //Prime the database with initial, minimum required data to boot and do things (manager account, locales)
    public static class PrimeData
    {

        /// <summary>
        /// Prime the database with manager account
        /// </summary>    
        public static void PrimeManagerAccount(AyContext ct)
        {
            //get a db and logger
            //ILogger log = AyaNova.Util.ApplicationLogging.CreateLogger("PrimeData");
            User u = new User();
            u.Active = true;
            u.Name = "AyaNova Administrator";
            u.Salt = Hasher.GenerateSalt();
            u.Login = "manager";
            u.Password = Hasher.hash(u.Salt, "l3tm3in");
            u.Roles = AuthorizationRoles.All;//AuthorizationRoles.BizAdminFull | AuthorizationRoles.OpsAdminFull | AuthorizationRoles.DispatchFull | AuthorizationRoles.InventoryFull;

            u.LocaleId = ServerBootConfig.AYANOVA_DEFAULT_LANGUAGE_ID;//Ensure primeLocales is called first
            u.UserType = UserType.Administrator;
            u.UserOptions = new UserOptions();
            ct.User.Add(u);
            ct.SaveChanges();

        }


        /// <summary>
        /// Prime the locales
        /// This may be called before there are any users on a fresh db boot 
        /// </summary>    
        public static void PrimeLocales()
        {//


            //Read in each stock locale from a text file and then create them in the DB
            var ResourceFolderPath = Path.Combine(ServerBootConfig.AYANOVA_CONTENT_ROOT_PATH, "resource");
            if (!Directory.Exists(ResourceFolderPath))
            {
                throw new System.Exception($"E1012: \"resource\" folder not found where expected: \"{ResourceFolderPath}\", installation damaged?");
            }


            ImportLocale(ResourceFolderPath, "en");
            ImportLocale(ResourceFolderPath, "es");
            ImportLocale(ResourceFolderPath, "fr");
            ImportLocale(ResourceFolderPath, "de");

            //Ensure locales are present, not missing any keys and that there is a server default locale that exists          

            LocaleBiz lb = LocaleBiz.GetBizInternal(ServiceProviderProvider.DBContext, 1, AuthorizationRoles.OpsAdminFull);
            lb.ValidateLocales();

        }

        private static void ImportLocale(string resourceFolderPath, string localeCode)
        {
            AyContext ct = ServiceProviderProvider.DBContext;
            var LocalePath = Path.Combine(resourceFolderPath, $"{localeCode}.json");
            if (!File.Exists(LocalePath))
            {
                throw new System.Exception($"E1013: stock locale file \"{localeCode}\" not found where expected: \"{LocalePath}\", installation damaged?");
            }

            JObject o = JObject.Parse(File.ReadAllText(LocalePath));

            Locale l = new Locale();
            l.Name = localeCode;

            l.Stock = true;
            l.CjkIndex = false;

            foreach (JToken t in o.Children())
            {
                var key = t.Path;
                var display = t.First.Value<string>();
                l.LocaleItems.Add(new LocaleItem() { Key = key, Display = display });//, Locale = l
            }

            ct.Locale.Add(l);
            ct.SaveChanges();
        }









    }//eoc

}//eons