using AipGateway.AIP;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using System.Net.Http.Headers;
using static AipGateway.API.Service.Models.ReqFileInfo;

namespace AipGateway.API.Service.Services
{
    public class AipFileManagerService : IAipFileManagerService
    {
        private readonly ILogger<AipFileManagerService> _logger;
        private readonly IConfiguration _configuration;

        private bool _isLoading;
        private AipConfig _aipConfig;
        private AipFileManager _aipFileManager = null;

        public AipFileManagerService()
        //public AipFileManagerService(ILogger<AipFileManagerService> logger)
        {
            _logger = null;
            _configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json", false).Build();

            _isLoading = false;

            _aipConfig = new AipConfig
            {
                AppName = _configuration["aip:AppName"], // 어플리케이션 이름
                AppVersion = _configuration["aip:AppVersion"], // 어플리케이션 버전
                ClientId = _configuration["aip:ClientId"], // 어플리케이션 ID(클라이언트 ID)
                TenantId = _configuration["aip:TenantId"], // 디렉토리(테넌트) ID
                MipData = _configuration["aip:MipData"], // Mip Data Path
                Domain = _configuration["aip:Domain"], // Domain
                EMail = _configuration["aip:EMail"], // User E-Mail
                SecretValue = _configuration["aip:SecretValue"], // 인증 비밀번호
                CertThumbPrint = _configuration["aip:CertThumbPrint"] // 인증서 지문
            };
            string tempLoginType = _configuration["aip:LoginType"];
            AipAuthLoginType loginType = (AipAuthLoginType)Enum.Parse(typeof(AipAuthLoginType), tempLoginType, true);
            _aipConfig.LoginType = loginType;

            _aipFileManager = new AipFileManager(_aipConfig);

            if (!_aipFileManager.Initialize())
            {
                Console.WriteLine("AipFileManagerService, _aipFileManager.Initialize Failed, {0}, {1}", _aipFileManager.LastErrNo, _aipFileManager.LastErrMsg);
                return;
            }
            if (!_aipFileManager.CreateProfile())
            {
                Console.WriteLine("AipFileManagerService, _aipFileManager.CreateProfile Failed, {0}, {1}", _aipFileManager.LastErrNo, _aipFileManager.LastErrMsg);
                return;
            }
            if (!_aipFileManager.CreateEngine())
            {
                Console.WriteLine("AipFileManagerService, _aipFileManager.CreateEngine Failed, {0}, {1}", _aipFileManager.LastErrNo, _aipFileManager.LastErrMsg);
                return;
            }
            _isLoading = true;
        }

        public async Task<AipConfig> GetConfig()
        {
            return _aipConfig;
        }
        public async Task<List<AipLabel>> GetLabels()
        {
            Console.WriteLine("AipFileManagerService::GetLabelsAsync: isLoading({0})", _isLoading);
            if (!_isLoading)
            {
                return null;
            }
            List<AipLabel> result = _aipFileManager.SensitivityLabels();
            return result;
        }

        public async Task<List<AipLabel>> GetPolicies()
        {
            Console.WriteLine("AipFileManagerService::GetPolicies: isLoading({0})", _isLoading);
            if (!_isLoading)
            {
                return null;
            }
            List<AipLabel> result = _aipFileManager.ListSensitivityLabels();
            return result;
        }
        public async Task<List<AipTemplate>> GetProtections()
        {
            Console.WriteLine("AipFileManagerService::GetProtections: isLoading({0})", _isLoading);
            if (!_isLoading)
            {
                return null;
            }
            List<AipTemplate> result = _aipFileManager.GetTemplates();
            return result;
        }

        public async Task<AipFileInfo> GetFileInfo(string fileName)
        {
            Console.WriteLine("AipFileManagerService::GetFileInfo-byFileName: isLoading({0})", _isLoading);
            if (!_isLoading)
            {
                return null;
            }
            AipFileInfo result = _aipFileManager.GetFileInfo(fileName);
            return result;
        }

        public async Task<AipFileInfo> GetFileInfo(Stream stream)
        {
            Console.WriteLine("AipFileManagerService::GetFileInfo-byFileStream: isLoading({0})", _isLoading);
            if (!_isLoading)
            {
                return null;
            }
            //if (streamArr == null || streamArr.Length == 0)
            //{
            //    return null;
            //}

            AipFileInfo result = null;
            //using (MemoryStream fileStream = new MemoryStream(stream))
            //{
                result = _aipFileManager.GetFileInfo(stream);
                if (result != null)
                {
                    if (result.OutputFileName != null)
                    {
                        using (var fileStream = File.Create(result.OutputFileName))
                        {
                            stream.Seek(0, SeekOrigin.Begin);
                            stream.CopyTo(fileStream);
                        }
                    }
                }
            //}
            return result;
        }

    }
}
