using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using AyaNova.Util;
using AyaNova.Models;
namespace AyaNova.Biz
{

    public class SearchTranslationWordBreakDataCache
    {
        static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
        private static Dictionary<long, TranslationWordBreakingData> theCache = new Dictionary<long, TranslationWordBreakingData>();
        public SearchTranslationWordBreakDataCache() { }
        public static async Task<TranslationWordBreakingData> GetWordBreakData(long id)
        {
            await semaphoreSlim.WaitAsync();
            try
            {
                if (!theCache.ContainsKey(id))
                    theCache.Add(id, await GetTranslationSearchDataAsync(id));
                return theCache.First(z=>z.Key==id).Value;
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }



        internal static async Task<TranslationWordBreakingData> GetTranslationSearchDataAsync(long translationId)
        {
            TranslationWordBreakingData LSD = new TranslationWordBreakingData();
            using (AyContext ct = ServiceProviderProvider.DBContext)
            {
                //Get stopwords
                //Validate translation id, if not right then use default instead 
                var Param = new List<string>();
                translationId = await TranslationBiz.ReturnSpecifiedTranslationIdIfExistsOrDefaultTranslationId(translationId, ct);
                Param.Add("StopWords1");
                Param.Add("StopWords2");
                Param.Add("StopWords3");
                Param.Add("StopWords4");
                Param.Add("StopWords5");
                Param.Add("StopWords6");
                Param.Add("StopWords7");
                var Stops = await TranslationBiz.GetSubsetStaticAsync(Param, translationId);

                foreach (KeyValuePair<string, string> kvp in Stops)
                {
                    //Each stopwords translation key is a space delimited list of words and in the case of an empty local string (i.e. StopWords7) it's value is a single question mark
                    if (kvp.Value != "?")
                    {
                        LSD.StopWords.AddRange(kvp.Value.Split(" "));
                    }
                }

                LSD.CJKIndex = await TranslationBiz.GetCJKIndexAsync(translationId, ct);
            }
            return LSD;
        }

        //Class to hold relevant translation data for breaking text
        public class TranslationWordBreakingData
        {
            public bool CJKIndex { get; set; }
            public List<string> StopWords { get; set; }
            public TranslationWordBreakingData()
            {
                CJKIndex = false;
                StopWords = new List<string>();
            }
        }

    }//eoc
}//eons