using CloudBuilder.Core.Application.Builders;
using CloudBuilder.Core.DatabaseAccessor.Entity;
using CloudBuilder.Core.Policy;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudBuilder.Core.DatabaseAccessor
{
    public class ApplicationService : IApplicationService
    {

        public ApplicationService(
                CloudBuilderBuilder cloudBuilder,
                IConfiguration configuration,
                IServiceProvider serviceProvider,
                IUnitOfWork unitOfWork,
                IHttpContextAccessor httpContext
            )
        {
            CloudBuilder = cloudBuilder;
            this.Configuration = configuration;
            this.ServiceProvider = serviceProvider;
            this.UnitOfWork = unitOfWork;
            this.HttpContext = httpContext;
            if (httpContext.HttpContext != null)
            {
                UserId = ClaimPolicy.GetClaimValue(HttpContext, ClaimPolicy.CLAINM_USERID);
                string key = ClaimPolicy.GetHeaderKeyValue(HttpContext, ClaimPolicy.HEADER_LOCALE);
                if (!string.IsNullOrEmpty(key))
                {
                    Locale = key;
                }
            }
        }

        public IServiceProvider ServiceProvider { get; private set; }

        public IHttpContextAccessor HttpContext { get; private set; }

        public string UserId { get;  set; }
        public string Locale { get; set; } = ClaimPolicy.CLAINM_LOCALE;
        public IUnitOfWork UnitOfWork { get; set; }
        public CloudBuilderBuilder CloudBuilder { get; set; }
        public IConfiguration Configuration { get; private set; }

        public KRepository GetRepository<KRepository>()
        {
            return ServiceProvider.GetRequiredService<KRepository>();
        }
    }
}
