master
1using System;
2using MVPtoMVVM.domain;
3using MVPtoMVVM.mvp.views;
4using MVPtoMVVM.repositories;
5
6namespace MVPtoMVVM.mvp.presenters
7{
8 public class TodoItemPresenter : ITodoItemPresenter
9 {
10 private ITodoItemRepository itemRepository;
11 private ITodoItemView view;
12 public int Id { get; set; }
13
14 public TodoItemPresenter(ITodoItemRepository itemRepository)
15 {
16 this.itemRepository = itemRepository;
17 }
18
19 public void SetView(ITodoItemView view)
20 {
21 this.view = view;
22 InitializeView();
23 }
24
25 private void InitializeView()
26 {
27 view.Id = Id;
28 view.Description = Description;
29 view.DueDate = DueDate;
30 view.SaveButtonEnabled = false;
31 }
32
33 private void UpdateControlState()
34 {
35 view.SaveButtonEnabled = IsDirty && IsDescriptionValid() && IsDueDateValid();
36 view.DescriptionHasValidationErrors = !IsDescriptionValid();
37 view.DescriptionValidationMessage = GetDescriptionValidationMessage();
38 view.DueDateHasValidationErrors = !IsDueDateValid();
39 view.DueDateValidationMessage = GetDueDateValidationMessage();
40 view.IsDueSoon = IsDueSoon();
41 }
42
43 public void SetItem(TodoItem item)
44 {
45 Id = item.Id;
46 Description = item.Description;
47 DueDate = item.DueDate;
48 IsDirty = false;
49 }
50
51 public void SaveItem()
52 {
53 var item = GetTodoItem();
54 itemRepository.Save(item);
55 Id = item.Id;
56 IsDirty = false;
57 }
58
59 private TodoItem GetTodoItem()
60 {
61 return new TodoItem {Id = Id, Description = Description, DueDate = DueDate};
62 }
63
64 public void DeleteItem()
65 {
66 var item = GetTodoItem();
67 view.Remove(item.Id);
68 itemRepository.Delete(item);
69 }
70
71 private string description;
72 public string Description
73 {
74 get { return description; }
75 set { description = value;
76 IsDirty = true;
77 }
78 }
79
80 private DateTime dueDate;
81 public DateTime DueDate
82 {
83 get { return dueDate; }
84 set { dueDate = value;
85 IsDirty = true;
86 }
87 }
88
89 private bool isDirty;
90
91
92 public bool IsDirty
93 {
94 get { return isDirty; }
95 private set { isDirty = value;
96 if (view != null)
97 UpdateControlState();
98 }
99 }
100
101 private bool IsDescriptionValid()
102 {
103 return description.Length > 0;
104 }
105
106 private bool IsDueDateValid()
107 {
108 return dueDate >= DateTime.Today;
109 }
110
111 private bool IsDueSoon()
112 {
113 return dueDate <= DateTime.Today.AddDays(1);
114 }
115
116 private string GetDescriptionValidationMessage()
117 {
118 return IsDescriptionValid() ? null : "You must enter a description";
119 }
120
121 private string GetDueDateValidationMessage()
122 {
123 return IsDueDateValid() ? null : "Due Date must be today or later";
124 }
125 }
126}