aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/ViewModels/MainViewVM.cs
blob: ea9470bb1d33fc15b37c85b0da95b3dca685a116 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
<UserControl x:Class="Tango.MachineStudio.RML.Views.ProcessParametersView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
            xmlns:global="clr-namespace:Tango.MachineStudio.RML"
             xmlns:observables="clr-namespace:Tango.BL.Entities;assembly=Tango.BL"
             xmlns:shapes="clr-namespace:Tango.SharedUI.Shapes;assembly=Tango.SharedUI"
             xmlns:controls="clr-namespace:Tango.SharedUI.Controls;assembly=Tango.SharedUI"
             xmlns:editors="clr-namespace:Tango.SharedUI.Editors;assembly=Tango.SharedUI"
             xmlns:mahapps="http://metro.mahapps.com/winfx/xaml/controls"
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
             xmlns:converters="clr-namespace:Tango.SharedUI.Converters;assembly=Tango.SharedUI"
             xmlns:dragAndDrop="clr-namespace:Tango.DragAndDrop;assembly=Tango.DragAndDrop"
             xmlns:vm="clr-namespace:Tango.MachineStudio.RML.ViewModels"
             xmlns:local="clr-namespace:Tango.MachineStudio.RML.Views"
             mc:Ignorable="d" 
             d:DesignHeight="1080" d:DesignWidth="1920" Background="Transparent" d:DataContext="{d:DesignInstance Type=vm:MainViewVM, IsDesignTimeCreatable=False}" DataContext="{x:Static global:ViewModelLocator.MainViewVM}">

    <UserControl.Resources>
        <converters:ColorToIntegerConverter x:Key="ColorToIntegerConverter"></converters:ColorToIntegerConverter>
    </UserControl.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="416*"/>
            <RowDefinition Height="120"/>
        </Grid.RowDefinitions>
        <Grid  Grid.Row="0">
            <DockPanel>
                <Border DockPanel.Dock="Top" Background="{StaticResource TransparentBackgroundBrush200}" Margin="20 0" Padding="5" CornerRadius="5">
                    <Border.Effect>
                        <DropShadowEffect Opacity="0.4" />
                    </Border.Effect>
                    <Grid>
                        <TextBlock HorizontalAlignment="Left" Margin="20 0 0 0" FontSize="16">ACTIVE PROCESS GROUP</TextBlock>
                        <Button ToolTip="Add new table" Style="{StaticResource MaterialDesignFlatButton}" Height="Auto" Width="30" HorizontalAlignment="Right" Padding="0" Command="{Binding AddProcessParametersTableCommand}">
                            <materialDesign:PackIcon Kind="Plus" Foreground="#0AC30A" Width="24" Height="24" />
                        </Button>
                    </Grid>
                </Border>
                <Grid>
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Margin="0 20">
                        <ItemsControl ItemsSource="{Binding ActiveProcessParametersTableView}">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <StackPanel HorizontalAlignment="Left" Orientation="Horizontal" />
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <DockPanel>
                                        <Button DockPanel.Dock="Right" Style="{StaticResource MaterialDesignFlatButton}" Padding="0" VerticalAlignment="Bottom" ToolTip="Remove table" Width="30" Margin="10 0 0 10" Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext.RemoveProcessParametersTableCommand}" CommandParameter="{Binding}">
                                            <materialDesign:PackIcon Kind="Delete" Width="24" Height="24" Foreground="#FF7D7D" />
                                        </Button>

                                        <Grid Style="{StaticResource draggableDroppableGrid}" dragAndDrop:DragAndDropService.Drop="OnProcessTableDropped">
                                            <Border Padding="5" BorderThickness="1" Margin="20 5 0 5" BorderBrush="{StaticResource DarkGrayBrush}" Background="{StaticResource TransparentBackgroundBrush100}">
                                                <Grid>
                                                    <DockPanel Width="300">
                                                        <TextBox materialDesign:HintAssist.Hint="Table Name" DockPanel.Dock="Top" Text="{Binding Name}"></TextBox>

                                                        <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto" Padding="5">
                                                            <editors:ParameterizedEditor ParameterizedObject="{Binding}">
                                                                <editors:ParameterizedEditor.ItemsPanel>
                                                                    <ItemsPanelTemplate>
                                                                        <StackPanel IsItemsHost="True" />
                                                                    </ItemsPanelTemplate>
                                                                </editors:ParameterizedEditor.ItemsPanel>
                                                                <editors:ParameterizedEditor.DoubleTemplate>
                                                                    <DataTemplate>
                                                                        <DockPanel>
                                                                            <TextBlock IsHitTestVisible="False" Margin="0 5 0 5" Text="{Binding Name}" FontSize="11"></TextBlock>
                                                                            <mahapps:NumericUpDown HorizontalAlignment="Right" Minimum="0" Margin="0 0 5 0" HideUpDownButtons="True" HorizontalContentAlignment="Right" Maximum="10000" StringFormat="0.0" InterceptArrowKeys="True" Background="Transparent" BorderThickness="0" InterceptMouseWheel="True" HasDecimals="True" Value="{Binding Value,Mode=TwoWay}"></mahapps:NumericUpDown>
                                                                        </DockPanel>
                                                                    </DataTemplate>
                                                                </editors:ParameterizedEditor.DoubleTemplate>
                                                            </editors:ParameterizedEditor>
                                                        </ScrollViewer>
                                                    </DockPanel>
                                                </Grid>
                                            </Border>

                                            <dragAndDrop:DragThumb Background="Transparent" Cursor="SizeAll" ToolTip="Drag and drop" Margin="0 3 -1 0" HorizontalAlignment="Right" VerticalAlignment="Top">
                                                <materialDesign:PackIcon HorizontalAlignment="Right" VerticalAlignment="Top" IsHitTestVisible="False" Kind="Drag" Width="32" Height="32" Background="Transparent" />
                                            </dragAndDrop:DragThumb>
                                        </Grid>
                                    </DockPanel>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </StackPanel>

                    <dragAndDrop:DraggingSurface x:Name="draggingSurface" ClipToBounds="True" />
                </Grid>
            </DockPanel>
        </Grid>
        <Grid Grid.Row="1">
            <DockPanel>
                <Grid>
                    <Grid  Margin="0 0 0 0">
                        <DockPanel>
                            <Border DockPanel.Dock="Top" Background="{StaticResource TransparentBackgroundBrush200}" Margin="20 0" Padding="5" CornerRadius="5">
                                <Border.Effect>
                                    <DropShadowEffect Opacity="0.4" />
                                </Border.Effect>
                                <Grid>
                                    <TextBlock HorizontalAlignment="Left" Margin="20 0 0 0" FontSize="16">LIQUID FACTORS</TextBlock>

                                    <Button ToolTip="Add new liquid factor" HorizontalAlignment="Right" Style="{StaticResource MaterialDesignFlatButton}" Height="Auto" VerticalAlignment="Bottom" Width="30" Padding="0" Command="{Binding AddLiquidFactorCommand}">
                                        <materialDesign:PackIcon Kind="Plus" Foreground="#0AC30A" Width="24" Height="24" />
                                    </Button>
                                </Grid>
                            </Border>
                            <ScrollViewer x:Name="liquidsFactorsScrollViewer" VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Hidden" Margin="15 0 20 0">
                                <ItemsControl Width="{Binding WidthLilquidFactors, RelativeSource={RelativeSource AncestorType=UserControl}}" ItemsSource="{Binding LiquidTypesRmls}" Margin="0 10 0 0">
                                    <ItemsControl.ItemsPanel>
                                        <ItemsPanelTemplate>
                                            <UniformGrid IsItemsHost="True" Rows="1"></UniformGrid>
                                        </ItemsPanelTemplate>
                                    </ItemsControl.ItemsPanel>
                                    <ItemsControl.ItemTemplate>
                                        <DataTemplate DataType="{x:Type observables:LiquidTypesRml}">
                                            <Grid Margin="20 0 20 0" MaxWidth="230">

                                                <Button HorizontalAlignment="Right" Style="{StaticResource MaterialDesignFlatButton}" Padding="0" ToolTip="Remove liquid factor" Width="30" Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext.RemoveLiquidFactorCommand}" CommandParameter="{Binding}">
                                                    <materialDesign:PackIcon Kind="Delete" Foreground="#FF7D7D" />
                                                </Button>

                                                <StackPanel Margin="0 0 10 0">
                                                    <TextBlock HorizontalAlignment="Center" FontSize="10" Foreground="{StaticResource MainWindow.Foreground}" Text="{Binding LiquidType.Name}"></TextBlock>
                                                    <Grid Width="58" Height="48" Margin="0 5 0 0">
                                                        <shapes:Hexagon StrokeThickness="1" Stroke="Gray">
                                                            <shapes:Hexagon.Fill>
                                                                <LinearGradientBrush Opacity="0.7" >
                                                                    <GradientStop Color="{Binding LiquidType.Color,Converter={StaticResource ColorToIntegerConverter}}"/>
                                                                    <GradientStop Color="White" Offset="1"/>
                                                                </LinearGradientBrush>
                                                            </shapes:Hexagon.Fill>
                                                        </shapes:Hexagon>

                                                        <TextBox Style="{x:Null}" Background="Transparent" Foreground="{StaticResource Hexagon.ForegroundBrush}" BorderThickness="0" Text="{Binding MaxNlPerCm}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"  FontStyle="Italic"></TextBox>
                                                    </Grid>
                                                </StackPanel>
                                            </Grid>
                                        </DataTemplate>
                                    </ItemsControl.ItemTemplate>
                                </ItemsControl>
                            </ScrollViewer>
                        </DockPanel>
                    </Grid>
                </Grid>
            </DockPanel>
        </Grid>
    </Grid>
</UserControl>
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using Tango.Core.Commands;
using Tango.Core.Helpers;
using Tango.BL.Entities;
using Tango.MachineStudio.Common.Notifications;
using Tango.SharedUI;
using SimpleValidator.Extensions;
using Tango.MachineStudio.Common.StudioApplication;
using Tango.MachineStudio.Common;
using Tango.BL;
using Tango.AutoComplete.Editors;
using System.Data.Entity;
using Tango.BL.Builders;
using Tango.MachineStudio.MachineDesigner.Contracts;
using System.Windows.Threading;
using Tango.Core.Threading;
using Tango.MachineStudio.RML.ViewModels;
using Tango.Settings;
using Tango.MachineStudio.RML.Models;
using Tango.BL.ActionLogs;
using Tango.MachineStudio.Common.Authentication;
using Tango.BL.DTO;
using Tango.Core.Cryptography;

namespace Tango.MachineStudio.MachineDesigner.ViewModels
{
    public class MainViewVM : StudioViewModel<IMainView>
    {
        private INotificationProvider _notification;
        private IActionLogManager _actionLogManager;
        private IAuthenticationProvider _authentication;
        private ActionTimer _machines_action_timer;
        private ActionTimer _dispensers_action_timer;
        private MachineDTO _machineBeforeSave;
        private List<Site> _all_sites;

        #region Properties

        private bool _isNewMachine;
        public bool IsNewMachine
        {
            get { return _isNewMachine; }
            set { _isNewMachine = value; RaisePropertyChangedAuto(); }
        }

        private ObservablesStaticCollections _machinesAdapter;
        public ObservablesStaticCollections MachinesAdapter
        {
            get { return _machinesAdapter; }
            set { _machinesAdapter = value; RaisePropertyChangedAuto(); }
        }

        private ObservablesStaticCollections _activeMachineAdapter;
        public ObservablesStaticCollections ActiveMachineAdapter
        {
            get { return _activeMachineAdapter; }
            set { _activeMachineAdapter = value; RaisePropertyChangedAuto(); }
        }

        private Machine _selectedMachine;
        /// <summary>
        /// Gets or sets the selected machine from the drop down.
        /// </summary>
        public Machine SelectedMachine
        {
            get { return _selectedMachine; }
            set
            {
                if (_selectedMachine != value)
                {
                    _selectedMachine = value;
                    RaisePropertyChangedAuto();
                    InvalidateRelayCommands();
                }
            }
        }

        private Machine _activeMachine;
        /// <summary>
        /// Gets or sets the active machine.
        /// </summary>
        public Machine ActiveMachine
        {
            get { return _activeMachine; }
            set { _activeMachine = value; RaisePropertyChangedAuto(); }
        }

        private IdsPack _selectedIds;
        /// <summary>
        /// Gets or sets the selected ids pack.
        /// </summary>
        public IdsPack SelectedIds
        {
            get { return _selectedIds; }
            set { _selectedIds = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); }
        }

        private String _dispensersFilter;
        /// <summary>
        /// Gets or sets the dispensers filter.
        /// </summary>
        public String DispensersFilter
        {
            get { return _dispensersFilter; }
            set { _dispensersFilter = value; RaisePropertyChangedAuto(); OnDispensersFilterChanged(); }
        }

        private String _filter;
        /// <summary>
        /// Gets or sets the machines filter.
        /// </summary>
        public String Filter
        {
            get { return _filter; }
            set { _filter = value; RaisePropertyChangedAuto(); OnFilterChanged(); }
        }

        private Spool _selectedSpool;
        public Spool SelectedSpool
        {
            get { return _selectedSpool; }
            set { _selectedSpool = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); }
        }

        private Site _selectedSite;
        public Site SelectedSite
        {
            get { return _selectedSite; }
            set { _selectedSite = value; RaisePropertyChangedAuto(); }
        }

        private List<Site> _sites;
        public List<Site> Sites
        {
            get { return _sites; }
            set { _sites = value; RaisePropertyChangedAuto(); }
        }


        private ColorCalibrationViewVM _colorCalibrationViewVM;
        public ColorCalibrationViewVM ColorCalibrationViewVM
        {
            get { return _colorCalibrationViewVM; }
            set { _colorCalibrationViewVM = value; RaisePropertyChangedAuto(); }
        }

        private HardwareConfigurationViewVM _hardwareConfigurationViewVM;
        public HardwareConfigurationViewVM HardwareConfigurationViewVM
        {
            get { return _hardwareConfigurationViewVM; }
            set
            {
                _hardwareConfigurationViewVM = value;
                RaisePropertyChangedAuto();
            }
        }

        private MachineUpdatesViewVM _machineUpdatesViewVM;
        public MachineUpdatesViewVM MachineUpdatesViewVM
        {
            get { return _machineUpdatesViewVM; }
            set { _machineUpdatesViewVM = value; RaisePropertyChangedAuto(); }
        }

        private TupViewVM _tupViewVM;
        public TupViewVM TupViewVM
        {
            get { return _tupViewVM; }
            set { _tupViewVM = value; RaisePropertyChangedAuto(); }
        }

        #endregion

        #region Commands

        /// <summary>
        /// Gets or sets the save command.
        /// </summary>
        public RelayCommand SaveCommand { get; set; }

        /// <summary>
        /// Gets or sets the add ids command.
        /// </summary>
        public RelayCommand AddIdsCommand { get; set; }

        /// <summary>
        /// Gets or sets the remove ids command.
        /// </summary>
        public RelayCommand RemoveIdsCommand { get; set; }

        /// <summary>
        /// Gets or sets the remove machine command.
        /// </summary>
        public RelayCommand RemoveMachineCommand { get; set; }

        /// <summary>
        /// Gets or sets the add machine command.
        /// </summary>
        public RelayCommand AddMachineCommand { get; set; }

        /// <summary>
        /// Gets or sets the edit machine command.
        /// </summary>
        public RelayCommand EditMachineCommand { get; set; }

        /// <summary>
        /// Gets or sets the back to machines command.
        /// </summary>
        public RelayCommand BackToMachinesCommand { get; set; }

        /// <summary>
        /// Gets or sets the add spool command.
        /// </summary>
        public RelayCommand AddSpoolCommand { get; set; }

        /// <summary>
        /// Gets or sets the remove spool command.
        /// </summary>
        public RelayCommand RemoveSpoolCommand { get; set; }

        /// <summary>
        /// Gets or sets the clone machine command.
        /// </summary>
        public RelayCommand CloneMachineCommand { get; set; }

        /// <summary>
        /// Gets or sets the reset device registration command.
        /// </summary>
        public RelayCommand ResetDeviceRegistrationCommand { get; set; }

        /// <summary>
        /// Gets or sets the make prototype command.
        /// </summary>
        public RelayCommand MakePrototypeCommand { get; set; }

        #endregion

        #region Constructors

        public MainViewVM()
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MainViewVM"/> class.
        /// </summary>
        public MainViewVM(INotificationProvider notification, IAuthenticationProvider authentication, IActionLogManager actionLogManager)
        {
            MachinesAdapter = new ObservablesStaticCollections(ObservablesContext.CreateDefault());
            _notification = notification;
            _authentication = authentication;
            _actionLogManager = actionLogManager;

            _machines_action_timer = new ActionTimer(TimeSpan.FromMilliseconds(200));
            _dispensers_action_timer = new ActionTimer(TimeSpan.FromMilliseconds(200));

            AddIdsCommand = new RelayCommand(AddIds, (x) => ActiveMachine != null && ActiveMachine.Configuration != null && ActiveMachine.Configuration.IdsPacks.Count < 9);
            RemoveIdsCommand = new RelayCommand(RemoveIds, (x) => SelectedIds != null);
            EditMachineCommand = new RelayCommand(() => LoadSelectedMachine(), () => SelectedMachine != null);
            BackToMachinesCommand = new RelayCommand(() => View.NavigateTo(MachineDesignerNavigationView.MachinesView));
            SaveCommand = new RelayCommand(SaveMachine);
            AddMachineCommand = new RelayCommand(AddNewMachine);
            RemoveMachineCommand = new RelayCommand(RemoveSelectedMachine, () => SelectedMachine != null);
            AddSpoolCommand = new RelayCommand(AddNewSpool);
            RemoveSpoolCommand = new RelayCommand(RemoveSpool, () => SelectedSpool != null);
            CloneMachineCommand = new RelayCommand(CloneMachine, () => SelectedMachine != null);
            ResetDeviceRegistrationCommand = new RelayCommand(ResetDeviceRegistration);
            MakePrototypeCommand = new RelayCommand(MakePrototype);

            MachineUpdatesViewVM = new MachineUpdatesViewVM(_notification);
            TupViewVM = new TupViewVM(_notification);
        }

        #endregion

        #region Application Ready

        public override async void OnApplicationReady()
        {
            MachinesAdapter.MachineVersions = (await MachinesAdapter.Context.MachineVersions.ToListAsync()).ToObservableCollection();

        }

        #endregion

        private void OnDispensersFilterChanged()
        {
            if (!String.IsNullOrWhiteSpace(DispensersFilter))
            {
                _dispensers_action_timer.ResetReplace(() =>
                {
                    Task.Factory.StartNew(() =>
                    {
                        ActiveMachineAdapter.Dispensers = ActiveMachineAdapter.Context.Dispensers.Where(x => x.SerialNumber.ToLower().StartsWith(DispensersFilter.ToLower())).OrderBy(x => x.SerialNumber).ToSynchronizedObservableCollection();
                    });
                });
            }
        }

        #region Drag Drop Handlers

        /// <summary>
        /// Drops the ids pack.
        /// </summary>
        /// <param name="idsPack1">The ids pack1.</param>
        /// <param name="idsPack2">The ids pack2.</param>
        public void DropIdsPack(IdsPack idsPack1, IdsPack idsPack2)
        {
            ActiveMachine.Configuration.IdsPacks.Swap(idsPack1, idsPack2);
            ColorCalibrationViewVM.InvalidateCalibrationDataAndColorConversion();
        }

        /// <summary>
        /// Drops the touch panel.
        /// </summary>
        /// <param name="applicationDisplayPanelVersion">The application display panel version.</param>
        public void DropTouchPanel(ApplicationDisplayPanelVersion applicationDisplayPanelVersion)
        {
            ActiveMachine.Configuration.ApplicationDisplayPanelVersion = applicationDisplayPanelVersion;
            ActiveMachine.Configuration.ApplicationDisplayPanelVersionGuid = applicationDisplayPanelVersion.Guid;
        }

        /// <summary>
        /// Drops the application firmware version.
        /// </summary>
        /// <param name="applicationFirmwareVersion">The application firmware version.</param>
        public void DropApplicationFirmwareVersion(ApplicationFirmwareVersion applicationFirmwareVersion)
        {
            ActiveMachine.Configuration.ApplicationFirmwareVersion = applicationFirmwareVersion;
            ActiveMachine.Configuration.ApplicationFirmwareVersionGuid = applicationFirmwareVersion.Guid;
        }

        /// <summary>
        /// Drops the hardware version.
        /// </summary>
        /// <param name="hardwareVersion">The hardware version.</param>
        public void DropHardwareVersion(HardwareVersion hardwareVersion)
        {
            ActiveMachine.Configuration.HardwareVersion = hardwareVersion;
            ActiveMachine.Configuration.HardwareVersionGuid = hardwareVersion.Guid;
        }

        /// <summary>
        /// Drops the embedded firmware.
        /// </summary>
        /// <param name="embeddedFirmwareVersion">The embedded firmware version.</param>
        public void DropEmbeddedFirmware(EmbeddedFirmwareVersion embeddedFirmwareVersion)
        {
            ActiveMachine.Configuration.EmbeddedFirmwareVersion = embeddedFirmwareVersion;
            ActiveMachine.Configuration.EmbeddedFirmwareVersionGuid = embeddedFirmwareVersion.Guid;
        }

        /// <summary>
        /// Drops the application os version.
        /// </summary>
        /// <param name="applicationOsVersion">The application os version.</param>
        public void DropApplicationOsVersion(ApplicationOsVersion applicationOsVersion)
        {
            ActiveMachine.Configuration.ApplicationOsVersion = applicationOsVersion;
            ActiveMachine.Configuration.ApplicationOsVersionGuid = applicationOsVersion.Guid;
        }

        /// <summary>
        /// Drops the dispenser.
        /// </summary>
        /// <param name="dispenser">The dispenser.</param>
        /// <param name="idsPack">The ids pack.</param>
        public void DropDispenser(Dispenser dispenser, IdsPack idsPack)
        {
            idsPack.Dispenser = dispenser;
            idsPack.DispenserGuid = dispenser.Guid;
        }

        /// <summary>
        /// Drops the type of the cartridge.
        /// </summary>
        /// <param name="cartridgeType">Type of the cartridge.</param>
        /// <param name="idsPack">The ids pack.</param>
        public void DropCartridgeType(CartridgeType cartridgeType, IdsPack idsPack)
        {
            idsPack.CartridgeType = cartridgeType;
            idsPack.CartridgeTypeGuid = cartridgeType.Guid;
        }

        /// <summary>
        /// Drops the type of the mid tank.
        /// </summary>
        /// <param name="midTankType">Type of the mid tank.</param>
        /// <param name="idsPack">The ids pack.</param>
        public void DropMidTankType(MidTankType midTankType, IdsPack idsPack)
        {
            idsPack.MidTankType = midTankType;
            idsPack.MidTankTypeGuid = midTankType.Guid;
        }

        /// <summary>
        /// Drops the type of the liquid.
        /// </summary>
        /// <param name="liquidType">Type of the liquid.</param>
        /// <param name="idsPack">The ids pack.</param>
        public void DropLiquidType(LiquidType liquidType, IdsPack idsPack)
        {
            idsPack.LiquidType = liquidType;
            idsPack.LiquidTypeGuid = liquidType.Guid;
            ColorCalibrationViewVM.InvalidateCalibrationDataAndColorConversion();
        }

        /// <summary>
        /// Drops the ids formula.
        /// </summary>
        /// <param name="idsPackFormula">The ids pack formula.</param>
        /// <param name="idsPack">The ids pack.</param>
        /// <exception cref="NotImplementedException"></exception>
        public void DropIdsFormula(IdsPackFormula idsPackFormula, IdsPack idsPack)
        {
            idsPack.IdsPackFormula = idsPackFormula;
            idsPack.IdsPackFormulaGuid = idsPackFormula.Guid;
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Removes the selected IDS pack.
        /// </summary>
        private void RemoveIds()
        {
            ActiveMachineAdapter.Context.IdsPacks.Remove(SelectedIds);
            SelectedIds = null;
            ColorCalibrationViewVM.InvalidateCalibrationDataAndColorConversion();
        }

        /// <summary>
        /// Adds a new IDS pack.
        /// </summary>
        private void AddIds()
        {
            ActiveMachineAdapter.Context.IdsPacks.Add(new IdsPack() { Configuration = ActiveMachine.Configuration });
            InvalidateRelayCommands();
        }

        private async void LoadSelectedMachine(bool newMachine = false, bool clone = false, MachineCreationDialogVM machineCreationDialogVM = null)
        {
            IsNewMachine = false;

            using (_notification.PushTaskItem("Loading machine details..."))
            {
                try
                {
                    IsFree = false;

                    if (ActiveMachineAdapter != null)
                    {
                        ActiveMachineAdapter.Context.Dispose();
                    }

                    ActiveMachineAdapter = new ObservablesStaticCollections(ObservablesContext.CreateDefault());
                    ActiveMachineAdapter.Organizations = (await ActiveMachineAdapter.Context.Organizations.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.MachineVersions = (await ActiveMachineAdapter.Context.MachineVersions.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.Rmls = (await ActiveMachineAdapter.Context.Rmls.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.ColorSpaces = (await ActiveMachineAdapter.Context.ColorSpaces.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.SpoolTypes = (await ActiveMachineAdapter.Context.SpoolTypes.ToListAsync()).ToObservableCollection();

                    ActiveMachineAdapter.ApplicationDisplayPanelVersions = (await ActiveMachineAdapter.Context.ApplicationDisplayPanelVersions.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.ApplicationFirmwareVersions = (await ActiveMachineAdapter.Context.ApplicationFirmwareVersions.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.ApplicationOsVersions = (await ActiveMachineAdapter.Context.ApplicationOsVersions.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.EmbeddedFirmwareVersions = (await ActiveMachineAdapter.Context.EmbeddedFirmwareVersions.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.DispenserTypes = (await ActiveMachineAdapter.Context.DispenserTypes.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.LiquidTypes = (await ActiveMachineAdapter.Context.LiquidTypes.ToListAsync()).OrderBy(x => x.PreferredIndex).ToObservableCollection();
                    ActiveMachineAdapter.MidTankTypes = (await ActiveMachineAdapter.Context.MidTankTypes.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.CartridgeTypes = (await ActiveMachineAdapter.Context.CartridgeTypes.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.IdsPackFormulas = (await ActiveMachineAdapter.Context.IdsPackFormulas.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.HardwareVersions = (await ActiveMachineAdapter.Context.HardwareVersions.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.MachineVersions = (await ActiveMachineAdapter.Context.MachineVersions.ToListAsync()).ToObservableCollection();
                    ActiveMachineAdapter.Organizations = (await ActiveMachineAdapter.Context.Organizations.ToListAsync()).ToObservableCollection();

                    bool initHwConfig = true;

                    Configuration machineConfigBeforeClone = null;

                    if (!newMachine)
                    {
                        ActiveMachine = (await new MachineBuilder(ActiveMachineAdapter.Context).Set(SelectedMachine.Guid).WithOrganization().WithConfiguration().WithSpools().BuildAsync());
                        _machineBeforeSave = MachineDTO.FromObservable(ActiveMachine);


                        if (clone)
                        {
                            machineConfigBeforeClone = ActiveMachine.Configuration;

                            IsNewMachine = true;
                            ActiveMachine = ActiveMachine.Clone();
                            ActiveMachine.Name = machineCreationDialogVM.Name;
                            ActiveMachine.SerialNumber = machineCreationDialogVM.SerialNumber;
                            ActiveMachine.IsDeviceRegistered = false;
                            ActiveMachine.DeviceId = null;
                            ActiveMachine.DeviceName = null;
                            ActiveMachine.ActivationKey = null;
                            ActiveMachineAdapter.Context.Machines.Add(ActiveMachine);
                        }
                    }
                    else
                    {
                        IsNewMachine = true;

                        if (machineCreationDialogVM.SelectedMachineVersion == null)
                        {
                            ActiveMachine = new Machine();
                            ActiveMachine.Configuration = new Configuration();
                            ActiveMachine.SerialNumber = machineCreationDialogVM.SerialNumber;
                            ActiveMachine.Name = machineCreationDialogVM.Name;
                            ActiveMachineAdapter.Context.Machines.Add(ActiveMachine);
                        }
                        else
                        {
                            try
                            {
                                initHwConfig = false;
                                ActiveMachine = await machineCreationDialogVM.SelectedMachineVersion.CreatePrototypeMachine(ActiveMachineAdapter.Context);
                                ActiveMachine.SerialNumber = machineCreationDialogVM.SerialNumber;
                                ActiveMachine.Name = machineCreationDialogVM.Name;
                                ActiveMachineAdapter.Context.Machines.Add(ActiveMachine);

                                HardwareConfigurationViewVM = new HardwareConfigurationViewVM(_notification);
                                var version = await new HardwareVersionBuilder(ActiveMachineAdapter.Context).Set(ActiveMachine.Configuration.HardwareVersionGuid).WithHardwareComponents().BuildAsync();
                                HardwareConfigurationViewVM.Init(ActiveMachine.Configuration);
                            }
                            catch (Exception ex)
                            {
                                _notification.ShowError($"Invalid machine version prototype.\n{ex.FlattenMessage()}");
                                View.NavigateTo(MachineDesignerNavigationView.MachinesView);
                                return;
                            }
                        }
                    }

                    if ((newMachine || clone) && machineCreationDialogVM.GenerateDispensers)
                    {
                        for (int i = 0; i < 9; i++)
                        {
                            var serial = machineCreationDialogVM.SerialNumber + "-" + (i + 1);

                            var existingDispenser = await ActiveMachineAdapter.Context.Dispensers.Include(x => x.IdsPacks).SingleOrDefaultAsync(x => x.SerialNumber == serial);

                            if (existingDispenser != null)
                            {
                                if (existingDispenser.IsInstalled)
                                {
                                    _notification.ShowError($"Dispenser '{serial}' already exists. Cannot create machine.");
                                    return;
                                }
                                else
                                {
                                    if (!_notification.ShowErrorQuestion($"Dispenser '{serial}' already exists and is not installed. Do you wish to assign the existing dispenser to this machine?"))
                                    {
                                        return;
                                    }
                                }
                            }

                            Dispenser dispenser = new Dispenser();

                            if (existingDispenser == null)
                            {
                                dispenser.SerialNumber = serial;

                                if (newMachine)
                                {
                                    dispenser.NlPerPulse = machineCreationDialogVM.DispenserFactor;
                                    dispenser.DispenserTypeGuid = ActiveMachineAdapter.DispenserTypes.First().Guid;
                                }
                                else
                                {
                                    var packBefore = machineConfigBeforeClone.NoneEmptyIdsPacks.SingleOrDefault(x => x.PackIndex == i);

                                    if (packBefore != null)
                                    {
                                        dispenser.NlPerPulse = packBefore.Dispenser.NlPerPulse;
                                        dispenser.DispenserTypeGuid = packBefore.Dispenser.DispenserType.Guid;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }

                                dispenser.ProductionDate = DateTime.UtcNow;

                                ActiveMachineAdapter.Context.Dispensers.Add(dispenser);
                            }
                            else
                            {
                                dispenser = existingDispenser;
                            }

                            var idsPack = ActiveMachine.Configuration.NoneEmptyIdsPacks.SingleOrDefault(x => x.PackIndex == i);

                            if (idsPack != null)
                            {
                                idsPack.Dispenser = dispenser;
                                idsPack.DispenserGuid = dispenser.Guid;
                            }
                        }
                    }
                    ActiveMachine.OrganizationChanged -= ActiveMachine_OrganizationChanged;
                    ActiveMachine.OrganizationChanged += ActiveMachine_OrganizationChanged;

                    _all_sites = await ActiveMachineAdapter.Context.Sites.ToListAsync();

                    var sites = ActiveMachine.Organization != null ? _all_sites.Where(x => x.OrganizationGuid == ActiveMachine.OrganizationGuid).ToList() : new List<Site>();
                    sites.Insert(0, new Site() { Name = "NONE", ID = -1 });
                    Sites = sites;

                    SelectedSite = Sites.SingleOrDefault(x => x.Guid == ActiveMachine.SiteGuid);

                    ColorCalibrationViewVM = new ColorCalibrationViewVM(_notification, ActiveMachine, _activeMachineAdapter.Context, ActiveMachineAdapter.Rmls.FirstOrDefault())
                    {
                        Rmls = ActiveMachineAdapter.Rmls,
                        LiquidTypesRmls = ActiveMachineAdapter.Rmls.FirstOrDefault().LiquidTypesRmls,
                    };

                    await ColorCalibrationViewVM.Invalidate();

                    if (initHwConfig)
                    {
                        HardwareConfigurationViewVM = new HardwareConfigurationViewVM(_notification);
                        HardwareConfigurationViewVM.Init(ActiveMachine.Configuration);
                    }

                    if (!IsNewMachine)
                    {
                        await MachineUpdatesViewVM.Init(ActiveMachine, ActiveMachineAdapter.Context);
                        TupViewVM.Init(ActiveMachine);
                    }

                    ActiveMachine.Configuration.HardwareVersionChanged += Configuration_HardwareVersionChanged;

                    while (ActiveMachine.ActivationKey == null) //Generate a random password and make sure no machine matches it.
                    {
                        ActiveMachine.ActivationKey = PasswordGenerator.Generate(8, PasswordGenerator.PasswordType.Alpha, PasswordGenerator.PasswordCasing.Upper);
                        if (await ActiveMachineAdapter.Context.Machines.Where(x => x.ActivationKey == ActiveMachine.ActivationKey).CountAsync() == 0)
                        {
                            break;
                        }

                        ActiveMachine.ActivationKey = null;
                    }

                    View.NavigateTo(MachineDesignerNavigationView.MachineDetailsView);
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, $"Error loading machine details for serial number {SelectedMachine.SerialNumber}");
                    _notification.ShowError($"An error occurred while trying to load the selected machine details.\n{ex.Message}");
                }
                finally
                {
                    IsFree = true;
                    InvalidateRelayCommands();
                }
            }
        }

        private async void Configuration_HardwareVersionChanged(object sender, HardwareVersion e)
        {
            var version = ActiveMachine.Configuration.HardwareVersion;

            if (version != null)
            {
                using (_notification.PushTaskItem("Loading hardware version..."))
                {
                    try
                    {
                        if (HardwareConfigurationViewVM == null)
                        {
                            HardwareConfigurationViewVM = new HardwareConfigurationViewVM(_notification);
                        }

                        version = await new HardwareVersionBuilder(ActiveMachineAdapter.Context).Set(version.Guid).WithHardwareComponents().BuildAsync();
                        HardwareConfigurationViewVM.Init(ActiveMachine.Configuration);
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex);
                    }
                }
            }
        }

        private async void SaveMachine()
        {
            foreach (var ids in ActiveMachine.Configuration.IdsPacks)
            {
                ids.PackIndex = ActiveMachine.Configuration.IdsPacks.IndexOf(ids);
                ids.Configuration = ActiveMachine.Configuration;
                ids.ConfigurationGuid = ActiveMachine.Configuration.Guid;
            }

            List<String> errors = new List<string>();

            if (ActiveMachine.MachineVersion == null)
            {
                errors.Add("Machine version is required.");
            }

            if (ActiveMachine.Name.IsNullOrWhiteSpace())
            {
                errors.Add("Machine name is required.");
            }

            if (ActiveMachine.Organization == null)
            {
                errors.Add("Machine organization is required.");
            }

            if (ActiveMachine.SerialNumber.IsNullOrWhiteSpace())
            {
                errors.Add("Machine serial number is required.");
            }

            if (ActiveMachine.Configuration.ApplicationDisplayPanelVersion == null)
            {
                errors.Add("Touch Panel is required.");
            }

            if (ActiveMachine.Configuration.ApplicationFirmwareVersion == null)
            {
                errors.Add("Application firmware is required.");
            }

            if (ActiveMachine.Configuration.ApplicationOsVersion == null)
            {
                errors.Add("Application operation system is required.");
            }

            if (ActiveMachine.Configuration.EmbeddedFirmwareVersion == null)
            {
                errors.Add("Embedded firmware is required.");
            }

            if (ActiveMachine.Configuration.HardwareVersion == null)
            {
                errors.Add("Hardware version is required.");
            }

            foreach (var pack in ActiveMachine.Configuration.IdsPacks)
            {
                if (pack.LiquidType != null || pack.CartridgeType != null || pack.Dispenser != null || pack.IdsPackFormula != null || pack.MidTankType != null)
                {
                    if (pack.CartridgeType == null)
                    {
                        errors.Add(String.Format("Cartridge type is required on IDS pack '{0}'.", pack.PackIndex));
                    }
                    if (pack.Dispenser == null)
                    {
                        errors.Add(String.Format("Dispenser is required on IDS pack '{0}'.", pack.PackIndex));
                    }
                    if (pack.LiquidType == null)
                    {
                        errors.Add(String.Format("Liquid type is required on IDS pack '{0}'.", pack.PackIndex));
                    }
                    if (pack.MidTankType == null)
                    {
                        errors.Add(String.Format("Mid Tank type is required on IDS pack '{0}'.", pack.PackIndex));
                    }
                    if (pack.IdsPackFormula == null)
                    {
                        errors.Add(String.Format("Formula type is required on IDS pack '{0}'.", pack.PackIndex));
                    }

                    pack.IsEmpty = false;
                }
                else
                {
                    pack.IsEmpty = true;
                }
            }

            foreach (var pack in ActiveMachine.Configuration.IdsPacks.Where(x => x.Dispenser != null))
            {
                if (ActiveMachine.Configuration.IdsPacks.Where(x => x.Dispenser == pack.Dispenser).Count() > 1)
                {
                    errors.Add($"Dispenser '{pack.Dispenser.SerialNumber}' is installed on multiple IDS packs.");
                }

                if (ActiveMachineAdapter.Context.IdsPacks.Count(x => x.ConfigurationGuid != pack.ConfigurationGuid && x.DispenserGuid == pack.DispenserGuid) > 0)
                {
                    errors.Add($"Dispenser '{pack.Dispenser.SerialNumber}' is already installed on a different machine.");
                }
            }

            if (ActiveMachine.Spools.GroupBy(x => x.SpoolType).Any(x => x.Count() > 1))
            {
                errors.Add($"Same spool type is registered multiple times.");
            }

            if (errors.Count > 0)
            {
                String errorsString = "Please fix the following validation errors before trying to save." + Environment.NewLine + Environment.NewLine;
                errorsString += String.Join(Environment.NewLine, errors.Distinct());
                _notification.ShowError(errorsString);
                return;
            }

            try
            {
                IsFree = false;

                using (_notification.PushTaskItem("Saving Machine Details..."))
                {

                    ActiveMachine.ConfigurationGuid = ActiveMachine.Configuration.Guid;
                    ActiveMachine.LastUpdated = DateTime.UtcNow;
                    ActiveMachine.SiteGuid = SelectedSite == null ? null : (SelectedSite.ID == -1 ? null : SelectedSite.Guid);

                    ColorCalibrationViewVM.Save();

                    var hwConfig = HardwareConfigurationViewVM.GetResultingHardwareConfiguration();
                    ActiveMachine.Configuration.SetHardwareConfiguration(hwConfig);
                    await ActiveMachineAdapter.Context.SaveChangesAsync();

                    if (IsNewMachine)
                    {
                        _actionLogManager.InsertLog(BL.Enumerations.ActionLogType.MachineCreated, _authentication.CurrentUser, ActiveMachine.Name, ActiveMachine, "New machine created using Machine Studio.");
                    }
                    else
                    {
                        var machineAfterDTO = MachineDTO.FromObservable(ActiveMachine);
                        _actionLogManager.InsertLog(BL.Enumerations.ActionLogType.MachineSaved, _authentication.CurrentUser, _machineBeforeSave.Name, _machineBeforeSave, machineAfterDTO, "Machine saved using Machine Studio.");
                        _machineBeforeSave = machineAfterDTO;
                    }

                    if (SelectedMachine != null)
                    {
                        await SelectedMachine.Reload(MachinesAdapter.Context);
                    }

                    await ColorCalibrationViewVM.Invalidate();
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error saving machine details.");
                _notification.ShowError("An error occurred while trying to save the machine details" + Environment.NewLine + ex.Message);
            }
            finally
            {
                IsFree = true;
                InvalidateRelayCommands();
            }
        }

        private void AddNewMachine()
        {
            MachineCreationDialogVM vm = new MachineCreationDialogVM();
            vm.IsNewMachine = true;
            vm.MachineVersions = MachinesAdapter.MachineVersions.ToList();
            _notification.ShowModalDialog<MachineCreationDialogVM, Views.MachineCreationDialog>(vm, (x) =>
            {
                if (MachinesAdapter.Context.Machines.Any(y => y.SerialNumber == vm.SerialNumber || y.Name.ToLower() == vm.Name.ToLower()))
                {
                    _notification.ShowError("Machine serial number or name already exists.");
                    return;
                }

                if (vm.SelectedMachineVersion != null && String.IsNullOrWhiteSpace(vm.SelectedMachineVersion.PrototypeMachineData))
                {
                    _notification.ShowError("The selected version does not contain any prototype machine data.");
                    return;
                }

                LoadSelectedMachine(true, false, vm);
            }, () => { });
        }

        private async void RemoveSelectedMachine()
        {
            if (_notification.ShowQuestion("Are you sure you want to delete the selected machine?"))
            {
                using (_notification.PushTaskItem("Removing machine..."))
                {
                    try
                    {
                        IsFree = false;
                        await SelectedMachine.DeleteCascadeAsync(MachinesAdapter.Context);
                        _actionLogManager.InsertLog(BL.Enumerations.ActionLogType.MachineDeleted, _authentication.CurrentUser, SelectedMachine.Name, SelectedMachine, "Machine deleted using Machine Studio.");
                        MachinesAdapter.Context.Machines.Remove(SelectedMachine);
                        MachinesAdapter.Machines.Remove(SelectedMachine);
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, $"Error removing machine {SelectedMachine.SerialNumber}.");
                        _notification.ShowError($"An error occurred while trying to delete the selected machine.\n{ex.Message}");
                    }
                    finally
                    {
                        IsFree = true;
                    }
                }
            }
        }

        private void ResetDeviceRegistration()
        {
            if (_notification.ShowQuestion("Are you sure you wish to reset this machine device registration?"))
            {
                ActiveMachine.IsDeviceRegistered = false;
                ActiveMachine.DeviceId = null;
                ActiveMachine.DeviceName = null;
            }
        }

        private async void MakePrototype()
        {
            if (ActiveMachine.MachineVersion == null)
            {
                _notification.ShowError("Machine version must be selected in order to make a prototype.");
                return;
            }

            if (_notification.ShowQuestion($"Are you sure you wish to make this machine configuration as a prototype for version '{ActiveMachine.MachineVersion.Name}' ?"))
            {
                using (_notification.PushTaskItem($"Making prototype machine for '{ActiveMachine.MachineVersion.Name}'..."))
                {
                    try
                    {
                        IsFree = false;

                        using (var db = ObservablesContext.CreateDefault())
                        {
                            var machineVersion = await db.MachineVersions.SingleOrDefaultAsync(x => x.Guid == ActiveMachine.MachineVersionGuid);
                            await machineVersion.ApplyPrototypeMachine(ActiveMachine, db);
                            await db.SaveChangesAsync();
                        }
                    }
                    catch (Exception ex)
                    {
                        _notification.ShowError($"Error making machine version prototype\n{ex.FlattenMessage()}");
                    }
                    finally
                    {
                        IsFree = true;
                    }
                }
            }
        }

        #endregion

        private void CloneMachine()
        {
            MachineCreationDialogVM vm = new MachineCreationDialogVM();
            vm.IsNewMachine = false;
            vm.MachineVersions = MachinesAdapter.MachineVersions.ToList();
            _notification.ShowModalDialog<MachineCreationDialogVM, Views.MachineCreationDialog>(vm, (x) =>
            {
                if (MachinesAdapter.Context.Machines.Any(y => y.SerialNumber == vm.SerialNumber || y.Name.ToLower() == vm.Name.ToLower()))
                {
                    _notification.ShowError("Machine serial number or name already exists.");
                    return;
                }

                LoadSelectedMachine(false, true, vm);
            }, () => { });
        }

        private void AddNewSpool()
        {
            _activeMachineAdapter.Context.Spools.Add(new Spool()
            {
                Machine = ActiveMachine,
            });
        }

        private void RemoveSpool()
        {
            if (SelectedSpool != null)
            {
                _activeMachineAdapter.Context.Spools.Remove(SelectedSpool);
                ActiveMachine.Spools.Remove(SelectedSpool);
            }
        }

        private void OnFilterChanged()
        {
            if (Filter != null)
            {
                _machines_action_timer.ResetReplace(() =>
                {
                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            IsFree = false;
                            MachinesAdapter.Machines = MachinesAdapter.Context.Machines.Where(x => x.SerialNumber.StartsWith(Filter)).Include(x => x.Organization).Include(x => x.MachineVersion).OrderBy(x => x.SerialNumber).ToSynchronizedObservableCollection();
                        }
                        catch
                        {

                        }
                        finally
                        {
                            IsFree = true;
                        }
                    });
                });
            }
        }

        private void ActiveMachine_OrganizationChanged(object sender, Organization e)
        {
            var sites = ActiveMachine.Organization != null ? _all_sites.Where(x => x.OrganizationGuid == ActiveMachine.OrganizationGuid).ToList() : new List<Site>();
            sites.Insert(0, new Site() { Name = "NONE", ID = -1 });
            Sites = sites;

            SelectedSite = Sites.SingleOrDefault(x => x.Guid == ActiveMachine.SiteGuid);
        }
    }
}