using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.InformationProtection;
using Microsoft.InformationProtection.Policy;

namespace AipGateway.AIP
{
    public class PolicyManager : AbstractManager
    {
        private IPolicyProfile _profile = null;
        private IPolicyEngine _engine = null;
        public PolicyManager()
        {
        }
        ~PolicyManager() => this.Dispose(false);

        public override void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize((object)this);

        }
        protected virtual void Dispose(bool disposing)
        {
            lock (this)
            {
                if (_profile != null && _engine != null)
                {
                    //_profile.UnloadEngineAsync(_engine.Settings.Id).Wait();
                    _profile.Dispose();
                    _engine.Dispose();

                }
                _engine = null;
                _profile = null;
            }
        }

        public override bool CreateProfile(ref MipContext mipContext)
        {
            try
            {
                var profileSettings = new PolicyProfileSettings(mipContext,
                    CacheStorageType.OnDiskEncrypted);

                // IFileProfile은 특정 애플리케이션에 대한 모든 SDK 작업의 루트입니다.
                _profile = Task.Run(async () => await MIP.LoadPolicyProfileAsync(profileSettings)).Result;
            }
            catch (Exception e)
            {
                SetError(1, "PolicyManager::CreateProfile Failed.", e.Message);
                return false;
            }
            return true;
        }

        public override bool CreateEngine(ref Identity identity, ref AuthDelegateImplementation authDelegate)
        {
            try
            {
                authDelegate.ResetError();
                var engineSettings = new PolicyEngineSettings(identity.Email, authDelegate, "", "en-US")
                {
                    // Provide the identity for service discovery.
                    Identity = identity
                };

                _engine = Task.Run(async () => await _profile.AddEngineAsync(engineSettings)).Result;

                Console.WriteLine("Policy Engine Sensitivity Labels ======================================================");
                var labels = _engine.ListSensitivityLabels();
                for (int ii = 0; ii < labels.Count; ii++)
                {
                    Console.WriteLine("{0}: {1}, {2}", ii.ToString(), labels[ii].Id + " : " + labels[ii].Name, labels[ii].IsActive);
                    Label label = _engine.GetLabelById(labels[ii].Id);
                    if (label.Children.Count > 0)
                    {
                        for (int jj = 0; jj < label.Children.Count; jj++)
                        {
                            Console.WriteLine("\t{0}: {1}, {2}", jj.ToString(), label.Children[jj].Id + " : " + label.Children[jj].Name, label.Children[jj].IsActive);
                        }
                    }
                }
                Console.WriteLine("=======================================================================");
            }
            catch (Exception e)
            {
                if (authDelegate.LastErrNo != 0)
                {
                    SetError(authDelegate.LastErrNo, "PolicyManager::CreateEngine Failed.", authDelegate.LastErrMsg);
                }
                else
                {
                    SetError(2, "PolicyManager::CreateEngine Failed.", e.Message);
                }

                return false;
            }
            return true;
        }

        public IEnumerable<Label> ListSensitivityLabels()
        {
            // 사용자 주체의 경우 이는 사용자별로 다릅니다.
            // 서비스 주체의 경우 이는 서비스별로 또는 전역적일 수 있습니다.
            return _engine.ListSensitivityLabels();
        }
    }

}
