using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using C4IT.Logging;
using C4IT.Security;
using C4IT.LIAM;

namespace LiamTestTeams
{
    public partial class frmMain : Form
    {
        private const string PPH = "uKl0P.&Wz8;?rpTL";
        private const string PPK = "f1JtsKzdeOB/rxG7geEwBumb7M0SoH8yMhv0Wi5G29LPpUwGmS6PzcynMnbc8ov5vOId5KJa4gHCDFgwCmXJZbApAG1QCUMwfIJSMaaowPAVcdSWbBHFEL50IpY+/YUKwl/B2pofNi2po0A7ZW00KVa6XFa5CpjFf6EGukwvL0jkEyK+RBoMYrUZWySQB1QS/AEohWCYo8ekcqV5PnBdXHZHyZB2bvK74ePhvJYnTnDUXbOpvEU19iHFzrJ0FxbZt1/2aPcyjHER8GhR7CXkxP2nJbn81bMzqLWQs3Wl1AWH+NbKvEY9+5NgkTqqvkW43Xkm5w8FwoEWIeX4yU50we9H060Dm6g8scyacL1MU0DKjOuxpxCE92fu6kp9DNQpSc6yCcwyzIS7atlwuqJ/N8nhuDcdH6X6hY/wrLgQjIrLi0I4n5vO6fT9hkusPaUHFpZVb2wPkHTJNzw+HF7fvhIROg50s273D5DmGioE0DyxkbJtg63R6LSPy8ok3W91qlD4+6DlPMPJ9ABLttK2ckcnMn/46YVDQ2ABpR7H79XgOf1NYp2WasLbC6KFE1ghpP0GEQughsxeVrNZhsZP351oEuCXVQx6w+iyp3Qv762vZ2vnh2G96drAHuOuLEqF+NZ7SVh3LGpuVE1bQbwd/9S3pdQI3iQcjza3Feoxew3RNaGnnJ63qLPVxc9dSvrRtVNwKOyW8iFdSpf1lHtX8XKPjOXSdhqOwts+Gl/Nn5bQee4uXdkrvxyN7wps1sWQRzkcyLIzplOwH80ZxEoVfgXz6lixMYOKrSly0kSektq6aRemfOBX7TvaQ+f1mgGripjks1UKUdrZG90Lj+WchTzDgxidHYW6z0vjxnO5mtnisryn8KnivpflC4y79/qZJ0ypPXCwKdH5QdvDEOhC2Qj8LX45YoCwanDIVgLbbz5lh9nbIMdH0uBkcbNAzNIjJwUTDWMcgzeeFJiEMKitISA4TpMTuxqKDjuqNa+S8qnYCy6A32O/TFihRIJG25w7khf0gnAdtkrCKOKsHwLKV1bdZxNW/WvA3WYSTIOvQIQsCre0YdqejUAiHLBPfh2ni4JVr2mU0AjulY7tnwsInxl2zR8FrgbziX0TxtXdrzTDMdIfCt1oFkiKUK9mwjlzBQ6Sl5G+wMmf4t8sQw1HTUvy/Ww1uu471+OUZui8npaRuKLG1m4+fvXRxF24YNxWNMCfGTsTOHCcxECwJhxMBDOQ8e6hYcXWDC5qMLnYKm1Gf2EVO5i7/vYtkRmK2SfP9b/Dg4BmW5/LUGEvUL4PT+xQVSHsJ+DZCB16fUfBgxMRoQZfR7U/Q/TCl5m6VCRT0AkcZDy3CiTemXbMylPpUKHURcPEYk6ALJgiuN8CQO+cxYZi16jx7/YJaINMx/855Gj4+fx/gWAdBLVwW2PT4jadx6lk7rwvO/wgPigwtLt6wxeqGbgWy3c2Ikdic7osZCThKD7Z+RPTVdpYudhkhs7Hd1sx+DBbX9fW/sKKONdquvvvKkHYbKV348IVKaMwSS/iSZ0YLwuNPMD3jtBhYoMeub9/SdkegUU0B5P8fA+uDdFppXazTpqgjApSJzkS";

        private readonly cLiamTestTeamsConfig Config = new cLiamTestTeamsConfig();

        public frmMain()
        {
            InitializeComponent();

            var SP = new cSecurePassword(PPH);
            SP.SetRsaKey(PPK, "C4IT_LIAM");
            cSecurePassword.Instance = SP;
        }

        private async void buttonLogin_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                if (tabControlLiam.TabPages.Contains(tabPageTeams))
                    tabControlLiam.TabPages.Remove(tabPageTeams);
                if (tabControlLiam.TabPages.Contains(tabPageLiam))
                    tabControlLiam.TabPages.Remove(tabPageLiam);

                textBoxDisplayName.Text = "";
                textBoxDomain.Text = "";

                var Provider = new cLiamProviderData()
                {
                    ProviderType = eLiamProviderTypes.MsTeams,
                    Domain = textBoxTenant.Text,
                    Credential = new cLiamCredential()
                    {
                        Domain = textBoxTenant.Text,
                        Identification = textBoxClientApp.Text,
                        Secret = textBoxClientSecret.Text
                    }
                };

                var RootNodeTeams = new TreeNodeMsTeamsRoot(Provider);

                if (!await RootNodeTeams.LogonAsync())
                {
                    groupBoxAccount.Text = "- Authentication error -";
                    labelError.Visible = true;
                    textBoxErrorMessage.Visible = true;
                    textBoxErrorMessage.Text = RootNodeTeams.getLastError();

                    textBoxDisplayName.Text = "";
                    textBoxDomain.Text = "";

                    return;
                }
                else
                {
                    labelError.Visible = false;
                    textBoxErrorMessage.Visible = false;
                    groupBoxAccount.Text = "Authenticated";

                    textBoxDisplayName.Text = RootNodeTeams.ToString();
                    textBoxDomain.Text = RootNodeTeams.GetInfoText();

                }

                if (!tabControlLiam.TabPages.Contains(tabPageTeams))
                    tabControlLiam.TabPages.Add(tabPageTeams);

                var RootNodeLiam = new TreeNodeLiamRoot(Provider);
                if (await RootNodeLiam.LogonAsync())
                {
                    if (!tabControlLiam.TabPages.Contains(tabPageLiam))
                        tabControlLiam.TabPages.Add(tabPageLiam);
                    await ctrlTabLiam1.Refresh(RootNodeLiam);
                }

                await ctrlTabTeams1.Refresh(RootNodeTeams);

                tabPageTeams.Select();

                return;
            }
            catch (Exception E)
            {
                ShowError(E.Message);
                cLogManager.LogException(E);
            }

            finally
            {
                Cursor = Cursors.Default;
            }

        }

        private void ShowError(string Message)
        {
            textBoxErrorMessage.Text = Message;
            labelError.Visible = true;
            textBoxErrorMessage.Visible = true;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            Config.Load();
            textBoxTenant.Text = Config.Tenant;
            textBoxClientApp.Text = Config.ClientAppID;
            if (!string.IsNullOrWhiteSpace(Config.ClientSecret))
                textBoxClientSecret.Text = cSecurePassword.Instance.Decode(Config.ClientSecret);

            ctrlTabLiam1.SetTitle("LIAM nodes:");
            ctrlTabTeams1.SetTitle("MS Teams");
            tabControlLiam.TabPages.Remove(tabPageTeams);
            tabControlLiam.TabPages.Remove(tabPageLiam);

            CheckLogin();
        }

        private void CheckLogin()
        {
            var enabled = false;
            if (!string.IsNullOrEmpty(textBoxTenant.Text))
                if (!string.IsNullOrEmpty(textBoxClientApp.Text))
                    if (!string.IsNullOrEmpty(textBoxClientSecret.Text))
                        enabled = true;
            buttonLogin.Enabled = enabled;
        }

        private void textBoxInput_TextChanged(object sender, EventArgs e)
        {
            CheckLogin();
        }
    }
}
