aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.DB/ViewModels/UsersViewVM.cs
blob: 1dde969d6571459f0b7d12e908bbb4d693027543 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.DAL.Observables;
using Tango.MachineStudio.Common.Notifications;

namespace Tango.MachineStudio.DB.ViewModels.DBViewModels
{
    public class UsersViewVM : DbTableViewModel<User>
    {
        private ObservableCollection<MultiComboVM<Role>> _selectedRoles;

        public UsersViewVM(INotificationProvider notification) : base(notification)
        {
            SelectedRoles = new ObservableCollection<MultiComboVM<Role>>();
        }

        public ObservableCollection<MultiComboVM<Role>> SelectedRoles
        {
            get { return _selectedRoles; }
            set { _selectedRoles = value; RaisePropertyChangedAuto(); }
        }

        protected override void OnEdit()
        {
            SelectedRoles = Adapter.Roles.Select(x => new MultiComboVM<Role>(x, () => RaisePropertyChanged(nameof(SelectedRoles)))).ToObservableCollection();

            foreach (var role in SelectedRoles)
            {
                if (SelectedEntity.UsersRoles.ToList().Exists(x => x.Role == role.Entity && !x.Deleted))
                {
                    role.IsSelected = true;
                }
            }

            base.OnEdit();
        }

        protected override void OnAdd()
        {
            SelectedRoles = Adapter.Roles.Select(x => new MultiComboVM<Role>(x, () => RaisePropertyChanged(nameof(SelectedRoles)))).ToObservableCollection();

            base.OnAdd();
        }

        protected override void OnBeforeEntitySave(DialogOpenMode mode, User user)
        {
            base.OnBeforeEntitySave(mode, user);

            foreach (var role in SelectedRoles)
            {
                var userRole = user.UsersRoles.SingleOrDefault(x => x.Role == role.Entity);

                if (userRole != null)
                {
                    userRole.Deleted = !role.IsSelected;
                }
                else
                {
                    if (role.IsSelected)
                    {
                        user.UsersRoles.Add(new UsersRole()
                        {
                            Role = role.Entity,
                            User = user,
                            RoleGuid = role.Entity.Guid,
                            UserGuid = user.Guid
                        });
                    }
                }
            }
        }
    }
}