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

namespace EnterpriseDesktop.Contacts.WinForm
{
    public partial class SaveContact : Form
    {
        public SaveContact()
        {
            InitializeComponent();

            contactDataSet.EnforceConstraints = false;
            contactBindingSource.AddNew();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // end editing on the binding source
            // if this is left off, things break!
            contactBindingSource.EndEdit();
            // establish web proxy
            EnterpriseDesktop.Contacts.Proxy.Web.Service proxy = new EnterpriseDesktop.Contacts.Proxy.Web.Service();
            // make asynchronous web service call
            proxy.ValidateContactCompleted += new EnterpriseDesktop.Contacts.Proxy.Web.ValidateContactCompletedEventHandler(proxy_ValidateContactCompleted);
            proxy.ValidateContactAsync(contactDataSet, Guid.NewGuid());
        }

        /// <summary>
        /// Checks to see if there are any errors, if so, it sets error providers
        /// automatically on the proper control(s).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void proxy_ValidateContactCompleted(object sender, EnterpriseDesktop.Contacts.Proxy.Web.ValidateContactCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                try
                {
                    string errors = String.Empty;
                    if (e.Result == null)
                    {
                        ResetErrorProvider();
                        MessageBox.Show("Contact is valid.", "Enterprise Desktop Validation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    HandleBrokenRules(e.Result);

                }
                catch
                {
                    MessageBox.Show("There was an error");
                }
            }
        }

        /// <summary>
        /// Takes a collection of broken rules and processes it accordingly.
        /// </summary>
        /// <param name="rules"></param>
        void HandleBrokenRules(Proxy.Web.Rule[] rules)
        {
            // reset errors if it runs again
            ResetErrorProvider();
            foreach (EnterpriseDesktop.Contacts.Proxy.Web.Rule rule in rules)
            {
                foreach (Control ctl in this.Controls)
                {
                    if (ctl is Label)
                    {
                        continue;
                    }
                    if (ctl.Name.ToLower().Contains(rule.property.ToLower()))
                    {
                        string prevError = errorProvider1.GetError(ctl).ToString();
                        if (!String.IsNullOrEmpty(prevError))
                        {
                            prevError += "\n";
                        }
                        errorProvider1.SetError(ctl,  prevError + rule.error);
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// Resets the error providers on all the form controls.
        /// </summary>
        void ResetErrorProvider()
        {
            foreach (Control ctl in this.Controls)
            {
                if (ctl is Label)
                {
                    continue;
                }
                errorProvider1.SetError(ctl, String.Empty);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // Before saving, make sure no errors are present
            Common.WinForm.FormValidation validation = new EnterpriseDesktop.Common.WinForm.FormValidation(this.Controls, errorProvider1);
            if (validation.FoundError)
            {
                validation.ShowErrors();
                return;
            }
            // end binding source edit
            contactBindingSource.EndEdit();
            Proxy.Web.Service proxy = new EnterpriseDesktop.Contacts.Proxy.Web.Service();
            proxy.SaveContactCompleted += new EnterpriseDesktop.Contacts.Proxy.Web.SaveContactCompletedEventHandler(proxy_SaveContactCompleted);
            proxy.SaveContactAsync(contactDataSet, Guid.NewGuid());
        }

        void proxy_SaveContactCompleted(object sender, EnterpriseDesktop.Contacts.Proxy.Web.SaveContactCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                if (e.brokenRules != null)
                {
                    if (e.brokenRules.Length > 0)
                    {
                        HandleBrokenRules(e.brokenRules);
                    }
                }
                else
                {
                    MessageBox.Show("Contact Saved", "Enterprise Desktop", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void firstNameTextBox_TextChanged(object sender, EventArgs e)
        {
            TextBox ctrl = sender as TextBox;
            Common.WinForm.Validation.ControlValidation.ValidateNameControl(ctrl, errorProvider1);
        }

        private void emailAddressTextBox_TextChanged(object sender, EventArgs e)
        {
            TextBox ctrl = sender as TextBox;
            Common.WinForm.Validation.ControlValidation.ValidateEmailAddressControl(ctrl, errorProvider1);
        }
    }
}