aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.MachineDesigner/ViewModels/MainViewVM.cs
blob: b0b97d7d4048fb024f032ba7e24029ba8985b001 (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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
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;

namespace Tango.MachineStudio.MachineDesigner.ViewModels
{
    public class MainViewVM : StudioViewModel<IMainView>
    {
        private INotificationProvider _notification;

        #region Properties

        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(); }
        }

        #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; }

        #endregion

        #region Constructors

        public MainViewVM()
        {

        }

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

            //SaveCommand = new RelayCommand(Save);
            AddIdsCommand = new RelayCommand(AddIds, (x) => ActiveMachine != null && ActiveMachine.Configuration != null && ActiveMachine.Configuration.IdsPacks.Count < 8);
            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);
        }

        #endregion

        #region Application Ready

        public override void OnApplicationReady()
        {

        }

        #endregion

        private async void OnDispensersFilterChanged()
        {
            if (!String.IsNullOrWhiteSpace(DispensersFilter))
            {
                IsFree = false;
                ActiveMachineAdapter.Dispensers = (await ActiveMachineAdapter.Context.Dispensers.Where(x => x.SerialNumber.ToLower().StartsWith(DispensersFilter.ToLower())).ToListAsync()).ToObservableCollection();
                IsFree = true;
            }
        }

        #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);
        }

        /// <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;
        }

        /// <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;
        }

        /// <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)
        {
            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()).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();

                    if (!newMachine)
                    {
                        ActiveMachine = (await new MachineBuilder(ActiveMachineAdapter.Context).Set(SelectedMachine.Guid).WithOrganization().WithConfiguration().WithSpools().BuildAsync());
                    }
                    else
                    {
                        ActiveMachine = new Machine();
                        ActiveMachine.Configuration = new Configuration();
                        ActiveMachineAdapter.Context.Machines.Add(ActiveMachine);
                    }

                    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 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 (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.ProductionDate = DateTime.UtcNow;
                    await ActiveMachineAdapter.Context.SaveChangesAsync();
                }
            }
            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()
        {
            LoadSelectedMachine(true);
        }

        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);
                        MachinesAdapter.Context.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;
                    }
                }
            }
        }

        #endregion

        private async void OnFilterChanged()
        {
            if (Filter != null)
            {
                IsFree = false;
                MachinesAdapter.Machines = (await MachinesAdapter.Context.Machines.Where(x => x.SerialNumber.StartsWith(Filter)).Include(x => x.Organization).Include(x => x.MachineVersion).ToListAsync()).ToObservableCollection();
                IsFree = true;
            }
        }
    }
}