using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Windows.Forms;
using System.Drawing;

namespace Foo.ClientServices.GUIWPForms
{    
    /// <summary>
    /// Interaction logic for WorkspaceSelector_RenameWorkspacePage.xaml
    /// </summary>
    public partial class WorkspaceSelector_RenameWorkspacePage : Page
    {
        // passed to us by parent
        private WorkspaceSelector m_WorkspaceSelectorObj = null;
        private bool m_bPerformanceCache = false;

        // private state variables
        private string m_strWorkspaceName;
        private bool m_bIsValidName;

        public WorkspaceSelector_RenameWorkspacePage(bool bPerformanceCache)
        {
            m_bPerformanceCache = bPerformanceCache;
            if (!m_bPerformanceCache)
            {                
            }
            InitializeComponent();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (!m_bPerformanceCache)
            {
                // Make sure that the Selector Frame is big enough to hold this page
                m_WorkspaceSelectorObj = (WorkspaceSelector)this.Tag;

                // Make sure that we have a workspace Name to work with otherwise Navigate Back
                if (String.IsNullOrEmpty(GUIState.LastSelectedWorkspaceName))
                    m_WorkspaceSelectorObj.NavigateToChildPage(ChildPages.WorkspaceSelector_StandardPage);
                else
                    m_strWorkspaceName = GUIState.LastSelectedWorkspaceName;

                // Set Height and Width
                m_WorkspaceSelectorObj.Height = this.Height + m_WorkspaceSelectorObj.MarginTopBottom;
                m_WorkspaceSelectorObj.Width = this.Width;

                // Set the Warning Label for this Particular Workspace
                ConstructAreYouSureMessage();

                // Set intial Error Message
                SetWarningMessage("Enter Characters");
                m_bIsValidName = false;

                // Set intial focus
                txtNewName.Focus();
            }
        }

        /// <summary>
        /// Constructs a renaming Message to be displayed to the user
        /// </summary>
        private void ConstructAreYouSureMessage()
        {            
            StringBuilder sr = new StringBuilder();
            sr.Append(String.Format("Rename Workspace '{0}'\n", m_strWorkspaceName));                                                            
            txtRenameWorkspaceTitle.Text = sr.ToString();
        }

        /// <summary>
        /// Sets the validator label to a warning message
        /// </summary>
        /// <param name="strMessage"></param>
        private void SetWarningMessage(string strMessage)
        {            
            lblWarningMessage.Foreground = new SolidColorBrush(Colors.OrangeRed);
            lblWarningMessage.Content = strMessage;
        }

        /// <summary>
        /// Sets the validator label to a success message
        /// </summary>
        /// <param name="strMessage"></param>
        private void SetSuccessMessage(string strMessage)
        {
            lblWarningMessage.Foreground = new SolidColorBrush(Colors.RoyalBlue);
            lblWarningMessage.Content = strMessage;
        }

        /// <summary>
        /// Button Yes Event Handler - Go ahead and Rename the WorkspaceName
        /// </summary>        
        private void btnYes_Click(object sender, RoutedEventArgs e)
        {
            if (m_bIsValidName)
            {
                if (!DataAccessLayer.Data.Workspace.RenameWorkspace(m_strWorkspaceName, txtNewName.Text))
                {
                    // an error occured
                    Foo.Platform.ErrorReporting.UserError.Show("An Error Occurred", "Renaming the Workspace Failed! Navigating you back to the WorkspaceSelector");
                    m_WorkspaceSelectorObj.NavigateToChildPage(ChildPages.WorkspaceSelector_StandardPage);
                }
                else
                {
                    // Set GUI State
                    GUIState.LastSelectedWorkspaceName = txtNewName.Text;

                    // Show Success Message
                    ShowMessageAndNavigateBack(String.Format("'{0}' has been successfully renamed to '{1}'", m_strWorkspaceName, txtNewName.Text));
                }
            }
        }

        /// <summary>
        /// Shows the passed in message in the text box and then navigates back to the main page
        /// </summary>
        /// <param name="strMessage"></param>
        private void ShowMessageAndNavigateBack(string strMessage)
        {
            // Hide the buttons
            btnYes.Visibility = Visibility.Hidden;
            btnNo.Visibility = Visibility.Hidden;

            // Hide the textbox and Labels
            lblEnterNewName.Visibility = Visibility.Hidden;
            txtNewName.Visibility = Visibility.Hidden;
            lblWarningMessage.Visibility = Visibility.Hidden;

            // Show Message
            txtRenameWorkspaceTitle.Text = strMessage;

            // Dynamically calculate the height of the textbox * No need to do this in this case *
            // System.Drawing.Size sz = new System.Drawing.Size((int)this.Width, int.MaxValue);
            // Font font = new Font(txtRenameWorkspaceTitle.FontFamily.ToString(),(float) txtRenameWorkspaceTitle.FontSize);
            // sz = TextRenderer.MeasureText(txtRenameWorkspaceTitle.Text, font, sz, TextFormatFlags.WordBreak);            
            // Change Height as needed
            // lblRenameWorkspaceTitle.Height = sz.Height;
            // txtRenameWorkspaceTitle.Height = sz.Height;

            // default to change height to Max available space
            lblRenameWorkspaceTitle.Height = this.Height - m_WorkspaceSelectorObj.MarginTopBottom;
            txtRenameWorkspaceTitle.Height = this.Height - m_WorkspaceSelectorObj.MarginTopBottom;
            
            // Pause for 1.5 second and Navigate Back
            DispatcherTimer dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 1, 500);
            dispatcherTimer.Start();
        }

        /// <summary>
        /// Timer set specifically to allow the message to be seen for a little bit before navigating back
        /// </summary>        
        void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            DispatcherTimer dispatcherTimer = (DispatcherTimer)sender;
            dispatcherTimer.Stop();

            // Navigate Back
            m_WorkspaceSelectorObj.NavigateToChildPage(ChildPages.WorkspaceSelector_StandardPage);
        }

        /// <summary>
        /// Button No Event Handler - Go back to parent
        /// </summary>        
        private void btnNo_Click(object sender, RoutedEventArgs e)
        {
            m_WorkspaceSelectorObj.NavigateToChildPage(ChildPages.WorkspaceSelector_StandardPage);
        }

        /// <summary>
        /// Perform NewWorkspaceName TextBox Validation
        /// </summary>        
        private void txtNewName_TextChanged(object sender, TextChangedEventArgs e)
        {
            System.Windows.Controls.TextBox textBox = (System.Windows.Controls.TextBox)sender;
            if (String.IsNullOrEmpty(textBox.Text))
            {
                SetWarningMessage("Enter Characters");
                m_bIsValidName = false;
            }
            else if (!DataAccessLayer.DataTypes.DataTypeValidation.IsValidWorkspaceName(textBox.Text))
            {
                SetWarningMessage("Invalid Workspace Name");
                m_bIsValidName = false;
            }
            else if (DataAccessLayer.Data.Workspace.DoesWorkspaceNameExist(textBox.Text))
            {
                SetWarningMessage("Workspace Name Already Exists");
                m_bIsValidName = false;
            }
            else
            {
                SetSuccessMessage("Valid Workspace Name");
                m_bIsValidName = true;
            }
        }
    }
}
