using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AipGateway.AIP;

namespace AipGateway.Viewer
{
    public partial class FrmMain : Form
    {
        private AipConfig _aipConfig;
        private AipFileManager _aipFileManager = null;
        private BindingList<object> fileLabels = new BindingList<object>();
        private BindingList<object> policyLabels = new BindingList<object>();
        private BindingList<object> protectTemplates = new BindingList<object>();

        public FrmMain()
        {
            InitializeComponent();
            Initialize();
        }

        private void Initialize()
        {
            TxtLog.Clear();
        
            // CboFileLabel.DataSource = fileLabels;
            // CboFileLabel.DisplayMember = "Display";
            // CboFileLabel.ValueMember = "Value";
            //
            // CboPolicyLabel.DataSource = policyLabels;
            // CboPolicyLabel.DisplayMember = "Display";
            // CboPolicyLabel.ValueMember = "Value";
            //
            // CboProtection.DataSource = protectTemplates;
            // CboProtection.DisplayMember = "Display";
            // CboProtection.ValueMember = "Value";
            // string value = CboFileLabel.SelectedValue.ToString();

            CboFileLabel.Items.Clear();
            CboPolicyLabel.Items.Clear();
            CboProtection.Items.Clear();
            CboAuthLoginType.SelectedIndex = -1;

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

            TxtAppName.Text = _aipConfig.AppName;
            TxtAppVer.Text = _aipConfig.AppVersion;
            TxtClientId.Text = _aipConfig.ClientId;
            TxtTenantId.Text = _aipConfig.TenantId;
            TxtMipData.Text = _aipConfig.MipData;
            TxtDomain.Text = _aipConfig.Domain;
            TxtEMail.Text = _aipConfig.EMail;
            TxtSecretValue.Text = _aipConfig.SecretValue;
            TxtCertThumbPrint.Text = _aipConfig.CertThumbPrint;
        }

        private void BtnFileSelect_Click(object sender, EventArgs e)
        {
            String inputFileName = ShowFileOpenDialog();
            TxtInputFile.Text = inputFileName;
            if (inputFileName != "")
            {
                string filePath = Path.GetDirectoryName(inputFileName);
                string fileName = Path.GetFileNameWithoutExtension(inputFileName);
                string fileExtension = Path.GetExtension(inputFileName);

                TxtActualFile.Text = filePath + Path.DirectorySeparatorChar + fileName + "-out" + fileExtension;
            }
            else
            {
                TxtActualFile.Text = "";
            }
        }
        private string ShowFileOpenDialog()
        {
            //파일오픈창 생성 및 설정
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "AIP 테스트 파일 선택";
            //ofd.FileName = "test";
            ofd.Filter = "모든 파일 (*.*) | *.*";

            //파일 오픈창 로드
            DialogResult dr = ofd.ShowDialog();

            //OK버튼 클릭시
            if (dr == DialogResult.OK)
            {
                // File명과 확장자를 가지고 온다.
                string fileName = ofd.SafeFileName;
                // File경로와 File명을 모두 가지고 온다.
                string fileFullName = ofd.FileName;
                // File경로만 가지고 온다.
                string filePath = fileFullName.Replace(fileName, "");

                //File경로 + 파일명 리턴
                return fileFullName;
            }
            //취소버튼 클릭시 또는 ESC키로 파일창을 종료 했을경우
            else if (dr == DialogResult.Cancel)
            {
                return "";
            }

            return "";
        }

        private void BtnInitialize_Click(object sender, EventArgs e)
        {
            _aipConfig.AppName = TxtAppName.Text.Trim();
            _aipConfig.AppVersion = TxtAppVer.Text.Trim();
            _aipConfig.ClientId = TxtClientId.Text.Trim();
            _aipConfig.TenantId = TxtTenantId.Text.Trim();
            _aipConfig.MipData = TxtMipData.Text.Trim();
            _aipConfig.Domain = TxtDomain.Text.Trim();
            _aipConfig.EMail = TxtEMail.Text.Trim();
            _aipConfig.SecretValue = TxtSecretValue.Text.Trim();
            _aipConfig.CertThumbPrint = TxtCertThumbPrint.Text.Trim();
            int loginType = CboAuthLoginType.SelectedIndex;
            if (loginType < 0)
            {
                MessageBox.Show("인증 로그인 방법을 선택 하세요.", "Initialize Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CboAuthLoginType.Focus();
                return;
            }
            _aipConfig.LoginType = (AipAuthLoginType)Enum.ToObject(typeof(AipAuthLoginType), loginType);

            SignOut();
            SignIn();
        }

        private void BtnSingOut_Click(object sender, EventArgs e)
        {
            SignOut();
        }

        private void SignIn()
        {
            _aipFileManager = new AipFileManager(_aipConfig);

            _aipFileManager.Initialize();
            _aipFileManager.CreateProfile();
            _aipFileManager.CreateEngine();

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("SensitivityLabels=======================================================================");
        
            BindingList<object> fileLabelList = new BindingList<object>();

            List<AipLabel> aipLabels = _aipFileManager.SensitivityLabels();
            foreach (var label in aipLabels)
            {
                ComboboxItem item = new ComboboxItem(label.Id, label.Name);
                CboFileLabel.Items.Add(item);

                sb.AppendLine(string.Format("ID: {0}, NAME: {1}", label.Id, label.Name));
                if (label.Children.Count > 0)
                {
                    foreach (AipLabel child in label.Children)
                    {
                        ComboboxItem childItem = new ComboboxItem(child.Id, "\t" + child.Name);
                        CboFileLabel.Items.Add(childItem);
                        sb.AppendLine(string.Format("\tID: {0}, NAME: {1}", child.Id, child.Name));
                    }
                }
            }

            sb.AppendLine("ListSensitivityLabels=======================================================================");
            List<AipLabel> labels2 = _aipFileManager.ListSensitivityLabels();
            foreach (var v in labels2)
            {
                ComboboxItem item = new ComboboxItem(v.Id, v.Name);
                CboPolicyLabel.Items.Add(item);
                sb.AppendLine(string.Format("Label List: {0}, {1}, {2}", v.Id, v.Name, v.IsActive));
                if (v.Children.Count > 0)
                {
                    foreach (AipLabel child in v.Children)
                    {
                        ComboboxItem childItem = new ComboboxItem(child.Id, "\t" + child.Name);
                        CboPolicyLabel.Items.Add(childItem);
                        sb.AppendLine(string.Format("\tID: {0}, NAME: {1}", child.Id, child.Name));
                    }
                }
            }

            sb.AppendLine("GetTemplates=======================================================================");
            List<AipTemplate> templates = _aipFileManager.GetTemplates();
            foreach (var v in templates)
            {
                ComboboxItem item = new ComboboxItem(v.Id, v.Name);
                CboProtection.Items.Add(item);
                sb.AppendLine(string.Format("Template: {0}, {1}, {2}", v.Id, v.Name, v.Description));
            }
            sb.AppendLine("=======================================================================");
            TxtLog.Text = sb.ToString();

            BtnInitialize.Enabled = false;
            BtnSingOut.Enabled = true;
        }
        private void SignOut()
        {
            BtnInitialize.Enabled = true;
            BtnSingOut.Enabled = false;

            CboFileLabel.Items.Clear();
            CboPolicyLabel.Items.Clear();
            CboProtection.Items.Clear();

            if (_aipFileManager != null)
            {
                _aipFileManager = null;
            }
        }

        private void AppendLog(string log)
        {
            TxtLog.Text += log + "\r\n";
        }
        private void BtnLogClear_Click(object sender, EventArgs e)
        {
            TxtLog.Clear();
        }

        private void BtnGetInfo_Click(object sender, EventArgs e)
        {
            TxtLog.Clear();
            string inputFileName = TxtInputFile.Text.Trim();
            if (inputFileName.Equals(""))
            {
                AppendLog("파일을 선택하세요.");
                return;
            }
        }
    }
}
