using CloudBuilder.Core.DatabaseAccessor.Entity;
using CloudBuilder.Core.DependencyInjection.Request;
using CloudBuilder.Core.Policy;
using CloudBuilder.Core.Service;
using CloudBuilder.Security.Entity;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudBuilder.Security.Service.DependencyInjection
{
    public class ServiceMessageManager : ILocaleMessageManager
    {
        public LocaleEntity[] LocaleEntities { get; set; } = null!;

        public static string SYSTEM = "system";
        public static string GUI_INFORMATION = "gui_information";
        public static string GUI_ERROR = "gui_error";
        private readonly IContext context;

        public IApplicationService Service { get; set; }

        private readonly IApplicationService service;

        private IRepository<LocaleEntity> repository;
        public ServiceMessageManager(IApplicationService service, IContext context)
        {
            this.service = service;
            this.context = context;
            repository = service.GetRepository<IRepository<LocaleEntity>>();
        }

        public void InitLocale()
        {
          
        }

        public string ComposeMessage(string groupName, string name)
        {
            LocaleEntity localeEntity = repository.DetachedEntities.Where(x => x.GroupName == groupName && x.Name == name && x.Lang == context.GetCulture()).FirstOrDefault()!;

            if (localeEntity == null) throw new ValidatedException();

            return localeEntity.Value;
        }

        public TableName<string>[] GetDataSource(string groupName)
        {
            string[] values = repository.DetachedEntities.Where(x => x.GroupName == groupName && x.Lang == context.GetCulture()).Select(x => x.Name).ToArray();

            return GetComposeMessages<string>(groupName, values);
        }

        public TableName<T>[] GetComposeMessages<T>(string groupName, T[] values)
        {
            if (values == null || values.Length == 0) return null;
            TableName<T> tb = null;
            List<TableName<T>> list = new List<TableName<T>>();
            foreach (T v in values)
            {
                tb = new TableName<T>();
                tb.DisplayName = ComposeMessage(groupName, v.ToString());
                tb.Value = v;
                list.Add(tb);
            }

            return list.ToArray();
        }
    }
}
