// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace Microsoft.Samples.WindowsAzureMmc.SnapIn.Forms
{
    using System;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Windows.Forms;
    using Microsoft.Samples.WindowsAzureMmc.SnapIn.Configuration;

    public partial class NewConnection : Form
    {
        public NewConnection()
        {
            InitializeComponent();
        }

        public NewConnection(ConfigurationData configData)
            : this()
        {
            Configuration = configData;
        }

        #region Properties
        /// <summary>
        /// The account name entered
        /// </summary>
        public string AccountName { get; private set; }
        /// <summary>
        /// The account key entered
        /// </summary>
        public string AccountKey { get; private set; }
        /// <summary>
        /// The url for the blob service
        /// </summary>
        public string BlobServiceURL { get; private set; }
        /// <summary>
        /// The url for the queue service
        /// </summary>
        public string QueueServiceURL { get; private set; }
        /// <summary>
        /// The configuration data contains a list of account used to ensure we dont have duplicates
        /// </summary>
        public ConfigurationData Configuration { get; private set; }

        #endregion


        /// <summary>
        /// Ok button clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OkButton_Click(object sender, EventArgs e)
        {
            if (isValid())
            {

                //Set properties
                AccountName = AccountNameText.Text;
                AccountKey = AccountKeyText.Text;
                BlobServiceURL = BlobServiceText.Text;
                QueueServiceURL = QueueServiceText.Text;

                //Return logon result
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }



        /// <summary>
        /// Update the urls when the account name is entered
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AccountNameText_TextChanged(object sender, EventArgs e)
        {
            updateUrls();
        }

        /// <summary>
        /// Update the urls when the Use Local check box is checked/unchecked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkUseLocal_CheckedChanged(object sender, EventArgs e)
        {
            updateUrls();
        }

        /// <summary>
        /// Update the urls based on the account name and local checkbox state
        /// </summary>
        private void updateUrls()
        {
            BlobServiceText.Text = "http://" + AccountNameText.Text + ".blob.core.windows.net";
            QueueServiceText.Text = "http://" + AccountNameText.Text + ".queue.core.windows.net";
        }

        /// <summary>
        /// Validate a url
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private bool isUrlOK(string url)
        {
            return Regex.IsMatch(url, @"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?");
        }

        /// <summary>
        /// Validate the form
        /// </summary>
        private bool isValid()
        {
            bool isValid = true;
            if (string.IsNullOrEmpty(AccountNameText.Text))
            {
                epDlg.SetError(AccountNameText, "Account Name must be entered");
                isValid = false;
            }
            else
            {
                // check for duplicate account names
                var dupeAccs = from acc in Configuration.Accounts
                               where acc.AccountName.ToUpperInvariant().CompareTo(AccountNameText.Text.ToUpperInvariant()) == 0
                               select acc;

                // make sure the account name if unique
                if (dupeAccs.Count() > 0)
                {
                    epDlg.SetError(AccountNameText, "Account Name must be unique");
                    isValid = false;
                }
                else
                {
                    epDlg.SetError(AccountNameText, null);
                }
            }


            if (string.IsNullOrEmpty(AccountKeyText.Text))
            {
                epDlg.SetError(AccountKeyText, "Account Key must be entered");
                isValid = false;
            }
            else
            {
                epDlg.SetError(AccountKeyText, null);
            }


            if (!isUrlOK(BlobServiceText.Text))
            {
                epDlg.SetError(BlobServiceText, "A valid BLOB Service Url must be entered");
                isValid = false;
            }
            else
            {
                epDlg.SetError(BlobServiceText, null);
            }

            if (!isUrlOK(QueueServiceText.Text))
            {
                epDlg.SetError(QueueServiceText, "A valid Queue Service Url must be entered");
                isValid = false;
            }
            else
            {
                epDlg.SetError(QueueServiceText, null);
            }

            return isValid;
        }
    }
}