using System.Threading.Tasks;
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, translations)
    public static class PrimeData
    {

        /// <summary>
        /// Prime the database with manager account
        /// </summary>    
        public static async Task 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.UserType = UserType.Administrator;
            u.UserOptions = new UserOptions();
            u.UserOptions.TranslationId = ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID;//Ensure primeTranslations is called first
            await ct.User.AddAsync(u);
            await ct.SaveChangesAsync();

        }


        /// <summary>
        /// Prime the Translations
        /// This may be called before there are any users on a fresh db boot 
        /// </summary>    
        public static async Task PrimeTranslations()
        {//


            //Read in each stock translation 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?");
            }


            await ImportTranslation(ResourceFolderPath, "en");
            await ImportTranslation(ResourceFolderPath, "es");
            await ImportTranslation(ResourceFolderPath, "fr");
            await ImportTranslation(ResourceFolderPath, "de");

            //Ensure Translations are present, not missing any keys and that there is a server default translation that exists  
            TranslationBiz lb = TranslationBiz.GetBiz(ServiceProviderProvider.DBContext);
            await lb.ValidateTranslationsAsync();

        }

        private static async Task ImportTranslation(string resourceFolderPath, string translationCode)
        {
            AyContext ct = ServiceProviderProvider.DBContext;
            var TranslationPath = Path.Combine(resourceFolderPath, $"{translationCode}.json");
            if (!File.Exists(TranslationPath))
            {
                throw new System.Exception($"E1013: stock translation file \"{translationCode}\" not found where expected: \"{TranslationPath}\", installation damaged?");
            }

            JObject o = JObject.Parse(await File.ReadAllTextAsync(TranslationPath));

            Translation l = new Translation();
            l.Name = translationCode;

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

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

            await ct.Translation.AddAsync(l);
            await ct.SaveChangesAsync();
        }









    }//eoc

}//eons