using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Data;

using BeWo.Core;
using BeWo.Core.Service;
using BeWo.ServiceProxy;
using BeWo.Validation;
using BeWo.ViewModel;
using BeWo.ViewModel.ListViewModel;

using BS.Shared;
using BS.Shared.Extensions;

using DevExpress.Xpf.Grid;

namespace BeWo.View.Detail
{
    public partial class TextbausteinView
    {
        private TextbausteinListVM _ViewModel;

        public TextbausteinListVM ViewModel
        {
            get { return _ViewModel; }

            set
            {
                _ViewModel = value;
                root.DataContext = value;
            }
        }

        public override bool IsDirty
        {
            get { return ViewModel != null && ViewModel.IsDirty; }
        }

        internal override DependencyObject ValidationOnSaveRootElement
        {
            get { return AddTextbausteinButton; }
        }

        private bool isInAdministrationView;

        public TextbausteinView(TextbausteinListVM pViewModel, bool pIsInAdministrationView = false)
        {
            InitializeComponent();

            isInAdministrationView = pIsInAdministrationView;

            EigenerTextbausteinSpalte.Visible = !isInAdministrationView;

            ViewModel = pViewModel;
        }

        protected override void Save()
        {
            var lToDos = new List<Action<IOperationsService>>();

            if (ViewModel.AddedCount > 0)
            {
                lToDos.Add(s => s.InsertNewTextbausteine(ViewModel.CommitAdded()));
            }

            if (ViewModel.RemovedCount > 0)
            {
                lToDos.Add(s => s.DeleteTextbausteine(ViewModel.GetRemoved().ToDictionary(dc => dc.TextbausteinOid.Value, dc => dc.TextbausteinVersion.Value)));
            }

            if (ViewModel.ChangedCount > 0)
            {
                lToDos.Add(s => s.UpdateTextbausteine(ViewModel.CommitChanged()));
            }

            ServiceFacade.DoMultipleOperationsServicesAsync(lToDos, ReloadViewModel);
        }

        public void Save(Action pCallBack)
        {
            var lToDos = new List<Action<IOperationsService>>();

            if (ViewModel.AddedCount > 0)
            {
                lToDos.Add(s => s.InsertNewTextbausteine(ViewModel.CommitAdded()));
            }

            if (ViewModel.RemovedCount > 0)
            {
                lToDos.Add(s => s.DeleteTextbausteine(ViewModel.GetRemoved().ToDictionary(dc => dc.TextbausteinOid.Value, dc => dc.TextbausteinVersion.Value)));
            }

            if (ViewModel.ChangedCount > 0)
            {
                lToDos.Add(s => s.UpdateTextbausteine(ViewModel.CommitChanged()));
            }

            ServiceFacade.DoMultipleOperationsServicesAsync(lToDos, pCallBack);
        }

        private void ReloadViewModel()
        {
            Cache.GetInstance().ClearServiceCategoryDescriptions();
            VMFactory.CreateTextbausteinListVMAsync(r => this.Dispatch(delegate
            {
                ViewModel = r;
            }), isInAdministrationView);
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.VMList.Remove(datagrid_textbausteine.GetCurrentValue<TextbausteinVM>());
            BeWoWpfUtils.RefreshDXGrid(datagrid_textbausteine);
        }

        private void ButtonAddTextbaustein_Click(object sender, RoutedEventArgs e)
        {
            if (ValidationTrigger.Validate(this))
            {
                ViewModel.AddNewVMToList();
            }
        }

        private void GridViewBase_OnShowingEditor(object sender, ShowingEditorEventArgs e)
        {
            if (e.Column.Header.Equals("Kategorie"))
            {
                var textbausteinVM = (TextbausteinVM) e.Row;

                e.Cancel = !CheckEditorRights(textbausteinVM, null);
            }
        }

        public static bool CheckEditorRights(TextbausteinVM textbausteinVM, object parameter)
        {
	        if (textbausteinVM != null)
	        {
                var isOwn = textbausteinVM.Employee.EmployeeOid.Equals(BeWoApp.LoggedOnEmployee.EmployeeOid);

		        var hasRight2EditAll = BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineAlleBearbeiten);
		        var hasRight2EditOwn = BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineNurEigeneBearbeiten);
		        var hasRight2Create4All = BeWoApp.LoggedOnUser.HasRight(UserRightType.TextbausteineAlleBearbeiten);

		        if (parameter != null && parameter.ToString().Equals("IsOnlyForEmployeeCheckBox"))
		        {
			        return isOwn && hasRight2EditOwn && hasRight2Create4All || hasRight2EditAll;
		        }

		        return isOwn && hasRight2EditOwn || hasRight2EditAll;
	        }
	        return false;
        }
    }

    public class IsOnlyForEmployeeRightsConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var textbausteinVM = (TextbausteinVM) value;

            return TextbausteinView.CheckEditorRights(textbausteinVM, parameter);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
