using FastReport.Forms;
using FastReport.Utils;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace FastReport.Auth
{
    /// <summary>
    /// Form for showing personalization information
    /// </summary>
    public partial class AuthFormOptions : DesignerOptionsPage
    {

        #region Private Fields

        private string expiresFormat;

        #endregion Private Fields

        #region Public Constructors

        /// <summary>
        /// Default constructor
        /// </summary>
        public AuthFormOptions()
        {
            InitializeComponent();
            Localize();
            AuthService.Instance.Refresh();
            UpdateInfo();
            RTL();
            comboBoxServerServer.SelectedIndex = 0;
        }

        #endregion Public Constructors

        #region Private Methods
        
        internal void UpdateCaptionFont(int dpi)
        {
            float scale = dpi == 0? 1f : dpi / 96f;
            lbCaption.Font = new Font("Calibri Light", 19.5f * scale );

            lbCaptionServer.Font = new Font("Calibri Light", 19.5f * scale );
            return;
        }


        private void btnSignIn_Click(object sender, EventArgs e)
        {
            AuthService.Instance.SignIn();
            UpdateInfo();
        }

        private void lbCreateOne_Click(object sender, EventArgs e)
        {
            ProcessHelper.StartProcess("https://id.fast-report.com/");
        }

        private void lbManage_Click(object sender, EventArgs e)
        {
            ProcessHelper.StartProcess("https://id.fast-report.com/");
        }

        private void lbSignOut_Click(object sender, EventArgs e)
        {
            AuthService.Instance.SignOut();
            UpdateInfo();
        }

        private void lbUpdate_Click(object sender, EventArgs e)
        {
            AuthService.Instance.SignIn();
            UpdateInfo();
        }
        //

        //server
        private void comboBoxServerServer_SelectedValueChanged(object sender, EventArgs e)
        {
            var comboBox = sender as ComboBox;
            var value = comboBox.SelectedItem as string;
            if (value == Res.Get("Forms,ServerWindow,comboBoxServer")) // pre-written server
            {
                textBoxCustomHostServer.Text = Res.Get("Forms,ServerWindow,comboBoxText");
                textBoxCustomHostServer.Enabled = false;
            }
            else    // Custom
            {
                textBoxCustomHostServer.Enabled = true;
                textBoxCustomHostServer.Text = "";
            }
        }

        private void textBoxCustomHostServer_TextChanged(object sender, EventArgs e)
        {
            var textBox = sender as TextBox;
            if (!textBox.Enabled)
                return;

            var requestHost = textBox.Text;
            if (string.IsNullOrEmpty(requestHost))
            {
            }
            else
            {
                AuthService.Instance.Settings.BackendHost = requestHost;
            }
        }

        private void textBoxApiKeyServer_TextChanged(object sender, EventArgs e)
        {
            var textBox = sender as TextBox;
            var text = textBox.Text;
            if (text != null)
            {
                var apiKey = text.Trim();
                if (apiKey != "")
                    AuthService.Instance.User.ApiKey = apiKey;
            }
        }


        private void Localize()
        {
            MyRes res = new MyRes("Forms,AccountWindow");

            this.Text = res.Get("");
            this.lbCaption.Text = res.Get("Title");
            this.btnSignIn.Text = res.Get("SignIn");
            this.lbNoAccount.Text = res.Get("NoAccount");
            this.lbCreateOne.Text = res.Get("Create");
            this.lbMessage.Text = res.Get("Intro") + res.Get("Testing");
            this.expiresFormat = res.Get("Expires");
            this.lbManage.Text = res.Get("Profile");
            this.lbSignOut.Text = res.Get("SignOut");
            this.lbText.Text = res.Get("Message");
            this.lbUpdate.Text = res.Get("SessionExpired");

            MyRes res2 = new MyRes("Forms,ServerWindow");

            this.label1Server.Text = res2.Get("Server");
            this.label2Server.Text = res2.Get("ApiKeyword");
            this.lbCaptionServer.Text = res2.Get("Caption");

            this.comboBoxServerServer.Items[0] = res2.Get("comboBoxServer");
            this.comboBoxServerServer.Items[1] = res2.Get("comboBoxCustom");
            this.tab2.Text = res2.Get("");

        }

        private void RightToLeftInternal(Control control)
        {
            if (control.HasChildren)
            {
                foreach (Control child in control.Controls)
                {
                    child.Left = control.Width - child.Left - child.Width;
                    RightToLeftInternal(child);
                }
            }
        }

        private Image RoundCorners(Image fromImage, float cornerRadius, Color backgroundColor)
        {
            cornerRadius *= 2;
            Bitmap result = new Bitmap(fromImage.Width, fromImage.Height);
            using (Graphics g = Graphics.FromImage(result))
            {
                g.Clear(backgroundColor);
                g.SmoothingMode = SmoothingMode.AntiAlias;
                using (Brush brush = new TextureBrush(fromImage))
                {
                    using (GraphicsPath gp = new GraphicsPath())
                    {
                        gp.AddArc(0, 0, cornerRadius, cornerRadius, 180, 90);
                        gp.AddArc(0 + result.Width - cornerRadius - 1, 0, cornerRadius, cornerRadius, 270, 90);
                        gp.AddArc(0 + result.Width - cornerRadius - 1, 0 + result.Height - cornerRadius - 1, cornerRadius, cornerRadius, 0, 90);
                        gp.AddArc(0, 0 + result.Height - cornerRadius, cornerRadius - 1, cornerRadius, 90, 90);
                        g.FillPath(brush, gp);
                        return result;
                    }
                }
            }
        }

        private void RTL()
        {
            if (RightToLeftLayout)
            {
                RightToLeftInternal(this);
            }
        }

        private void UpdateInfo()
        {
            AuthService auth = AuthService.Instance;
            if (auth.User.IsAuthenticated)
            {
                BeforeSignIn(false);
                AfterSignIn(true);
                lbUsername.Text = auth.User.DisplayName;
                lbEmail.Text = auth.User.DisplayEmail;
                pbAvatar.Image = RoundCorners(auth.User.DisplayAvatar, 15, Color.Transparent);

                if (auth.CanRefresh)
                {
                    if (auth.User.ExpiresIn < DateTime.Now)
                    {
                        lbTime.Visible = false;
                        lbUpdate.Visible = true;
                    }
                    else
                    {
                        lbUpdate.Visible = false;
                        lbTime.Visible = true;
                        lbTime.Text = String.Format(expiresFormat, auth.User.ExpiresIn.ToShortTimeString());
                    }
                }

            }
            else
            {
                this.SuspendLayout();
                BeforeSignIn(true);
                AfterSignIn(false);
            }
        }

        private void BeforeSignIn(bool visible)
        {
            this.tab1.SuspendLayout();

            lbMessage.Visible = visible;
            btnSignIn.Visible = visible;
            lbCreateOne.Visible = visible;
            lbNoAccount.Visible = visible;

            this.tab1.PerformLayout();
        }

        private void AfterSignIn(bool visible)
        {
            
            this.tab1.SuspendLayout();

            lbUpdate.Visible = visible;
            lbTime.Visible = visible;
            pbAvatar.Visible = visible;
            lbText.Visible = visible;
            lbSignOut.Visible = visible;
            lbManage.Visible = visible;
            lbUsername.Visible = visible;
            lbEmail.Visible = visible;

            tab1.ResumeLayout(true);
        }

        #endregion Private Methods

    }
}