using System;
using System.Windows.Forms;
using FastReport.Utils;
using FastReport.Cloud.StorageClient.SkyDrive;

namespace FastReport.Cloud.StorageClient.GoogleDrive
{
    /// <summary>
    /// Represents form of Google Drive storage client.
    /// </summary>
    public partial class GoogleDriveStorageClientForm : CloudStorageClientForm
    {
        #region Fields

        private GoogleDriveStorageClient client;

        #endregion // Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="GoogleDriveStorageClientForm"/> class.
        /// </summary>
        public GoogleDriveStorageClientForm() : base()
        {
            client = new GoogleDriveStorageClient();
            InitializeComponent();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="GoogleDriveStorageClientForm"/> class.
        /// </summary>
        /// <param name="clientInfo">The information about Google Drive client application.</param>
        /// <param name="report">The report template.</param>
        public GoogleDriveStorageClientForm(ClientInfo clientInfo, Report report) : base(report)
        {
            client = new GoogleDriveStorageClient(clientInfo);
            InitializeComponent();
        }

        #endregion // Constructors

        #region Protected Methods

        /// <inheritdoc/>
        protected override void Init()
        {
            base.Init();

            XmlItem xi = Config.Root.FindItem("GoogleDriveCloud").FindItem("StorageSettings");
            string id = xi.GetProp("ClientId");
            string secret = xi.GetProp("ClientSecret");
            if (!String.IsNullOrEmpty(id) && !String.IsNullOrEmpty(secret))
            {
                client.ClientInfo.Id = id;
                client.ClientInfo.Secret = secret;
            }
            client.AuthCode = xi.GetProp("AuthCode");
            string str = xi.GetProp("IsUserAuthorized");
            if (String.IsNullOrEmpty(str))
            {
                client.IsUserAuthorized = false;
            }
            else
            {
                client.IsUserAuthorized = Convert.ToBoolean(str);
            }
            string accessToken = xi.GetProp("AccessToken");
            if (!String.IsNullOrEmpty(accessToken))
            {
                client.AccessToken = accessToken;
            }

            tbServer.Text = xi.GetProp("Server");
            tbPort.Text = xi.GetProp("Port");
            tbUsername.Text = xi.GetProp("Username");
            tbPassword.Text = xi.GetProp("Password");
        }

        /// <inheritdoc/>
        protected override bool Done()
        {
            if (base.Done())
            {
                XmlItem xi = Config.Root.FindItem("GoogleDriveCloud").FindItem("StorageSettings");
                xi.SetProp("ClientId", client.ClientInfo.Id);
                xi.SetProp("ClientSecret", client.ClientInfo.Secret);
                xi.SetProp("AuthCode", client.AuthCode);
                xi.SetProp("IsUserAuthorized", client.IsUserAuthorized.ToString());
                xi.SetProp("AccessToken", client.AccessToken);
                xi.SetProp("Server", tbServer.Text);
                xi.SetProp("Port", tbPort.Text);
                xi.SetProp("Username", tbUsername.Text);
                xi.SetProp("Password", tbPassword.Text);
                return true;
            }
            return false;
        }

        #endregion // Protected Methods

        #region Public Methods

        /// <inheritdoc/>
        public override void Localize()
        {
            base.Localize();

            MyRes res = new MyRes("Cloud,GoogleDrive");
            this.Text = res.Get("");
        }

        #endregion // Public Methods

        #region Events Handlers

        /// <inheritdoc/>
        protected override void btnOk_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            if (!client.IsUserAuthorized || String.IsNullOrEmpty(client.AccessToken))
            {
                string authorizationUrl = client.GetAuthorizationUrl();
                WebBrowserForm browser = new WebBrowserForm(authorizationUrl);
                browser.ShowDialog();
                client.AuthCode = browser.AuthCode;
                client.IsUserAuthorized = true;
                client.GetAccessToken();
            }
            client.ProxySettings = GetProxySettings();
            bool saved = false;
            try
            {
                client.SaveReport(Report, Exports[cbFileType.SelectedIndex]);
                saved = true;
            }
            catch { }
            if (!saved)
            {
                string authorizationUrl = client.GetAuthorizationUrl();
                WebBrowserForm browser = new WebBrowserForm(authorizationUrl);
                browser.ShowDialog();
                client.AuthCode = browser.AuthCode;
                client.IsUserAuthorized = true;
                client.GetAccessToken();
                client.ProxySettings = GetProxySettings();
                try
                {
                    client.SaveReport(Report, Exports[cbFileType.SelectedIndex]);
                }
                catch (CloudStorageException ex)
                {
                    MessageBox.Show(ex.Message, Res.Get("Messages,Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            DialogResult = DialogResult.OK;
            Close();
        }

        #endregion // Events Handlers
    }
}

