using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.InformationProtection;
using Microsoft.InformationProtection.File;
using Microsoft.InformationProtection.Policy;
using Microsoft.InformationProtection.Protection;
using LogLevel = Microsoft.InformationProtection.LogLevel;

namespace AipGateway.AIP
{
    public class AipFileManager
    {
        public int LastErrNo { get; internal set; }
        public string LastErrMsg { get; internal set; }

        private readonly AipConfig _aipConfig;

        private readonly ApplicationInfo _appInfo;
        private AuthDelegateImplementation _authDelegate;

        private MipContext _mipContext;

        private readonly LabelManager _labelManager = null;
        private readonly PolicyManager _policyManager = null;
        private readonly ProtectionManager _protectionManager = null;

        // public LabelManager GetLabelManager()
        // {
        //     return _labelManager;
        // }
        // public PolicyManager GetPolicyManager()
        // {
        //     return _policyManager;
        // }
        // public ProtectionManager GetProtectionManager()
        // {
        //     return _protectionManager;
        // }

        public AipFileManager(AipConfig aipConfig)
        {
            _aipConfig = aipConfig;
            _appInfo = new ApplicationInfo
            {
                ApplicationId = aipConfig.ClientId,
                ApplicationName = aipConfig.AppName,
                ApplicationVersion = aipConfig.AppVersion
            };
            LastErrNo = 0;
            LastErrMsg = string.Empty;

            _labelManager = new LabelManager();
            _policyManager = new PolicyManager();
            _protectionManager = new ProtectionManager();
        }
        ~AipFileManager() => this.Dispose(false);
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize((object)this);

        }
        protected virtual void Dispose(bool disposing)
        {
            lock (this)
            {
                if (_labelManager != null)
                {
                    _labelManager.Dispose();
                }
                if (_policyManager != null)
                {
                    _policyManager.Dispose();
                }
                if (_protectionManager != null)
                {
                    _protectionManager.Dispose();
                }

                _authDelegate = null;
            }
        }

        private void SetError(int errNo, string errMsg1, string errMsg2 = "No Exception Message.")
        {
            LastErrNo = errNo;
            LastErrMsg = errMsg1 + "\r\n" + errMsg2;
            Console.WriteLine("AipFileManager::SetError ==> {0}, {1}, {2}", errNo, errMsg1, errMsg2);
        }


        public bool Initialize()
        {
            _authDelegate = new AuthDelegateImplementation(_aipConfig);
            try {
                // Initialize SDK DLLs. If DLLs are missing or wrong type, this will throw an exception
                MIP.Initialize(MipComponent.File);
                //MIP.Initialize(MipComponent.Policy);
                //MIP.Initialize(MipComponent.Protection);    // Protection
            }
            catch (Exception ex) {
                SetError(1, "MIP.Initialize Failed.", ex.Message);
                return false;
            }

            // Create MipConfiguration Object
            var mipConfiguration = new MipConfiguration(_appInfo, _aipConfig.MipData, LogLevel.Trace, false);

            // Create MipContext using MipConfiguration
            _mipContext = MIP.CreateMipContext(mipConfiguration);

            return true;
        }

        public bool CreateProfile()
        {
            if (!_labelManager.CreateProfile(ref _mipContext))
            {
                SetError(11, "AipFileManager::CreateProfile ==> LabelManager::CreateProfile Failed.");
                return false;
            }
            if (!_policyManager.CreateProfile(ref _mipContext))
            {
                SetError(12, "AipFileManager::CreateProfile ==> PolicyManager::CreateProfile Failed.");
                return false;
            }
            if (!_protectionManager.CreateProfile(ref _mipContext))
            {
                SetError(13, "AipFileManager::CreateProfile ==> ProtectionManager::CreateProfile Failed.");
                return false;
            }

            return true;
        }

        public bool CreateEngine()
        {
            Identity identity = new Identity(_aipConfig.EMail);

            if (!_labelManager.CreateEngine(ref identity, ref _authDelegate))
            {
                SetError(21, "AipFileManager::CreateEngine ==> LabelManager::CreateEngine Failed.");
                return false;
            }
            if (!_policyManager.CreateEngine(ref identity, ref _authDelegate))
            {
                SetError(22, "AipFileManager::CreateEngine ==> PolicyManager::CreateEngine Failed.");
                return false;
            }
            if (!_protectionManager.CreateEngine(ref identity, ref _authDelegate))
            {
                SetError(23, "AipFileManager::CreateEngine ==> ProtectionManager::CreateEngine Failed.");
                return false;
            }

            return true;
        }

        public void GetFileInfo(string fileName)
        {
            _labelManager.GetFileInfo(fileName);
        }
        public List<AipLabel> SensitivityLabels()
        {
            var result = new List<AipLabel>();
            try
            {
                var labels = _labelManager.SensitivityLabels();
                foreach (var label in labels)
                {
                    var aipLabel = new AipLabel
                    {
                        Id = label.Id,
                        Name = label.Name,
                        Sensitivity = label.Sensitivity,
                        Description = label.Description,
                        IsActive = label.IsActive,
                    };
                    aipLabel.Children = new List<AipLabel>();

                    // If the label has an children, iterate through each. 
                    if (label.Children.Count > 0)
                    {
                        foreach (var child in label.Children)
                        {
                            var aipChildLabel = new AipLabel
                            {
                                Id = child.Id,
                                Name = child.Name,
                                Sensitivity = child.Sensitivity,
                                Description = child.Description,
                                IsActive = child.IsActive,
                            };

                            aipLabel.Children.Add(aipChildLabel);
                        }
                    }
                    result.Add(aipLabel);
                }
            }
            catch (Exception ex)
            {
                SetError(31, "AipFileManager::SensitivityLabels Failed.", ex.Message);
                result = new List<AipLabel>();
            }
            return result;
        }

        public List<AipLabel> ListSensitivityLabels()
        {
            var result = new List<AipLabel>();
            try
            {
                var labels = _policyManager.ListSensitivityLabels();
                foreach (var label in labels)
                {
                    var aipLabel = new AipLabel
                    {
                        Id = label.Id,
                        Name = label.Name,
                        Sensitivity = label.Sensitivity,
                        Description = label.Description,
                        IsActive = label.IsActive,
                    };
                    aipLabel.Children = new List<AipLabel>();

                    // If the label has an children, iterate through each. 
                    if (label.Children.Count > 0)
                    {
                        foreach (var child in label.Children)
                        {
                            var aipChildLabel = new AipLabel
                            {
                                Id = child.Id,
                                Name = child.Name,
                                Sensitivity = child.Sensitivity,
                                Description = child.Description,
                                IsActive = child.IsActive,
                            };

                            aipLabel.Children.Add(aipChildLabel);
                        }
                    }
                    result.Add(aipLabel);
                }
            }
            catch (Exception ex)
            {
                SetError(32, "AipFileManager::ListSensitivityLabels Failed.", ex.Message);
                result = new List<AipLabel>();
            }
            return result;
        }

        public List<AipTemplate> GetTemplates()
        {
            var result = new List<AipTemplate>();
            try
            {
                var labels = _protectionManager.GetTemplates();
                foreach (var label in labels)
                {
                    var aipTemplate = new AipTemplate
                    {
                        Id = label.Id,
                        Name = label.Name,
                        Description = label.Description
                    };

                    result.Add(aipTemplate);
                }
            }
            catch (Exception ex)
            {
                SetError(33, "AipFileManager::GetTemplates Failed.", ex.Message);
                result = new List<AipTemplate>();
            }
            return result;
        }
    }
}
