using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Microsoft.Practices.CompositeUI.EventBroker;
using Microsoft.Practices.ObjectBuilder;
using Uniframework.Security;

namespace Uniframework.Common.WorkItems.Authorization
{
    public partial class CommandView : DevExpress.XtraEditors.XtraUserControl
    {
        public CommandView()
        {
            InitializeComponent();
        }

        #region Dependency Services

        private CommandPresenter presenter;
        [CreateNew]
        public CommandPresenter Presenter
        {
            get { return presenter; }
            set {
                presenter = value;
                presenter.View = this;
            }
        }

        #endregion

        public AuthorizationNode AuthNode
        {
            get;
            set;
        }

        private void edtImage_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

        }

        /// <summary>
        /// Handles the Click event of the btnOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (AuthNode == null) // ²Ù×÷Ä£ÄâµÄ±£´æ¹¤×÷
            {
                Presenter.AuthorizationCommandService.Delete(edtCommandUri.Text);
                AuthorizationCommand command = new AuthorizationCommand() {
                    Name = edtName.Text,
                    CommandUri = edtCommandUri.Text,
                    Category = edtCategory.Text
                };
                if ((!String.IsNullOrEmpty(edtImage.Text) || edtImage.Text.Length != 0)
                    && edtImage.Text.IndexOf("${") == -1)
                    command.Image = "${" + Path.GetFileNameWithoutExtension(edtImage.Text) + "}";


                try {
                    Presenter.AuthorizationCommandService.Save(command);
                    btnOK.DialogResult = DialogResult.OK;
                }
                catch (Exception ex) {
                    XtraMessageBox.Show("±£´æÃüÁî \"" + edtName.Text + "\" Ê±Ê§°Ü£¬" + ex.Message);
                    btnOK.DialogResult = DialogResult.None;
                }
            }
            else {
                AuthorizationCommand command = new AuthorizationCommand() { 
                    Name = edtName.Text,
                    CommandUri = edtCommandUri.Text,
                    Category = edtCategory.Text
                };
                if ((!String.IsNullOrEmpty(edtImage.Text) || edtImage.Text.Length != 0)
                    && edtImage.Text.IndexOf("${") == -1)
                    command.Image = "${" + Path.GetFileNameWithoutExtension(edtImage.Text) + "}";

                foreach (AuthorizationCommand cmd in AuthNode.Commands) {
                    // É¾³ýÁÐ±íÖÐÔ­À´µÄ²Ù×÷Ïî
                    if (cmd.Name == command.Name || cmd.CommandUri == command.CommandUri) {
                        AuthNode.RemoveCommand(cmd);
                        break;
                    }
                }

                // ±£´æÐÂµÄ²Ù×÷
                AuthNode.AddCommand(command);
                if (!Presenter.AuthorizationCommandService.Exists(command.Name, command.CommandUri))
                    Presenter.AuthorizationCommandService.Save(command); // ±£´æµ½²Ù×÷Ä£°åÖÐÈ¥
                try {
                    Presenter.AuthorizationNodeService.Save(AuthNode);
                    btnOK.DialogResult = DialogResult.OK;
                }
                catch (Exception ex) {
                    XtraMessageBox.Show("±£´æ²Ù×÷ \"" + edtName.Text + "\" Ê±¼äÊ§°Ü£¬" + ex.Message);
                    btnOK.DialogResult = DialogResult.None;
                }
            }
        }

        private void edtName_Leave(object sender, EventArgs e)
        {
            labPreview.Text = edtName.Text;
        }

        /// <summary>
        /// ¶©ÔÄÁÐ±íÖÐµ±Ç°ÃüÁî±ä»¯ÊÂ¼þ
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Uniframework.EventArgs&lt;Uniframework.Security.AuthorizationCommand&gt;"/> instance containing the event data.</param>
        [EventSubscription(EventNames.Authorization_CurrentCommandChanged, ThreadOption.UserInterface)]
        public void OnCurrentCommandChanged(object sender, EventArgs<AuthorizationCommand> e)
        {
            edtName.Text = e.Data.Name;
            edtCommandUri.Text = e.Data.CommandUri;
            edtCategory.Text = e.Data.Category;
            edtImage.Text = e.Data.Image;

            // ÏÔÊ¾Í¼±ê
            if (!String.IsNullOrEmpty(edtImage.Text))
                image.ContentImage = Presenter.ImageService.GetBitmap(edtImage.Text);
        }

        /// <summary>
        /// Bindings the command.
        /// </summary>
        /// <param name="command">The command.</param>
        public void BindingCommand(AuthorizationCommand command)
        {
            edtName.Text = command.Name;
            edtCommandUri.Text = command.CommandUri;
            edtCategory.Text = command.Category;
            edtImage.Text = command.Image;

            if (!String.IsNullOrEmpty(edtImage.Text))
                image.ContentImage = Presenter.ImageService.GetBitmap(edtImage.Text);
        }

        private void edtImage_Leave(object sender, EventArgs e)
        {
            edtImage_ButtonClick(this, null);
        }
    }
}
