using System;
using System.Windows;
using TaskIt.Modules.Tasks.ViewModels;
using TaskIt.ViewModels;

namespace TaskIt.Modules.Tasks.Views
{
    public partial class RowDetailTabs
    {
        public RowDetailTabs()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            if (IsInitialized)
            {
                return;
            }

            NotesListView = new NotesViews.List();
            NotesDetailsView = new NotesViews.Details();
            NotesControlContainer.Content = NotesListView;

            AttachmentsListView = new AttachmentsViews.List();
            AttachmentsControlContainer.Content = AttachmentsListView;

            var isInGrid = ViewModelProxy != null;

            // If used in a data grid's RowDetailsTemplate, set the DataContext to the DataSource property (which will have been bound to the ViewModel)
            if (isInGrid)
            {
                DataContext = ViewModelProxy;
                NotesListView.IsInGrid = true;
                AttachmentsListView.IsInGrid = true;
            }

            ViewModel.ViewNoteForm += OnViewNoteForm;
            ViewModel.ViewNoteList += OnViewNoteList;

            IsInitialized = true;
        }

        void OnViewNoteForm(object sender, RoutedEventArgs e)
        {
            if (NotesControlContainer.Content == NotesDetailsView)
            {
                return;
            }
            NotesControlContainer.Content = NotesDetailsView;
        }

        void OnViewNoteList(object sender, RoutedEventArgs e)
        {
            if (NotesControlContainer.Content == NotesListView)
            {
                return;
            }
            NotesControlContainer.Content = NotesListView;
        }

        private NotesViews.List NotesListView { get; set; }

        private NotesViews.Details NotesDetailsView { get; set; }

        private AttachmentsViews.List AttachmentsListView { get; set; }

        private bool IsInitialized { get; set; }

        public Object ViewModelProxy
        {
            get { return GetValue(ViewModelProxyProperty); }
            set { SetValue(ViewModelProxyProperty, value); }
        }

        public static readonly DependencyProperty ViewModelProxyProperty =
            DependencyProperty.Register("ViewModelProxy", typeof(TaskItViewModelBase), typeof(RowDetailTabs), null);

        private TasksViewModelBase ViewModel
        {
            get { return DataContext as TasksViewModelBase; }
        }
    }
}