summaryrefslogtreecommitdiff
path: root/src/MVPtoMVVM.mvvm/viewmodels/MainWindowViewModel.cs
blob: 5ca0d7f3c5969df949d66ec51b2189dc374b02e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Windows.Input;
using MVPtoMVVM.domain;
using MVPtoMVVM.repositories;

namespace MVPtoMVVM.mvvm.viewmodels
{
    public class MainWindowViewModel : INotifyPropertyChanged
    {
        private ITodoItemRepository todoItemRepository;
        private Synchronizer<MainWindowViewModel> updater;
        public event PropertyChangedEventHandler PropertyChanged = (o, e) => { };
        public ICollection<TodoItemViewModel> TodoItems { get; set; }
        public ICommand CancelChangesCommand { get; set; }
        public ICommand AddNewItemCommand { get; set; }

        public MainWindowViewModel(ITodoItemRepository todoItemRepository)
        {
            this.todoItemRepository = todoItemRepository;
            AddNewItemCommand = new SimpleCommand(AddNewItem);
            CancelChangesCommand = new SimpleCommand(RefreshChanges);
            updater = new Synchronizer<MainWindowViewModel>(() => PropertyChanged);
            TodoItems = new ObservableCollection<TodoItemViewModel>();
            RefreshChanges();
        }

        private void RefreshChanges()
        {
            TodoItems.Clear();
            foreach (var item in todoItemRepository.GetAll().Select(MapFrom))
            {
                TodoItems.Add(item);
            }
        }

        private void AddNewItem()
        {
            TodoItems.Add(new TodoItemViewModel(todoItemRepository){Parent =  this, DueDate = DateTime.Today, Description = string.Empty, IsDirty = false});
        }

        private TodoItemViewModel MapFrom(TodoItem item)
        {
            return new TodoItemViewModel(todoItemRepository)
                       {
                           Id = item.Id,
                           Description =  item.Description,
                           DueDate = item.DueDate,                                                                        
                           Parent = this,
                           IsDirty = false,
                       };
        }

        public void Update(Expression<Func<MainWindowViewModel, object>> property)
        {
            updater.Update(this, property);
        }
    }
}