aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.RML/ViewModels/MainViewVM.cs
blob: ef6fc816bb672b682d735b51268299787c8140c5 (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
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using Tango.BL;
using Tango.BL.Builders;
using Tango.BL.Calibration;
using Tango.BL.Entities;
using Tango.Core.Commands;
using Tango.MachineStudio.ColorLab.ViewModels;
using Tango.MachineStudio.Common;
using Tango.MachineStudio.Common.Notifications;
using Tango.MachineStudio.RML.Contracts;
using Tango.MachineStudio.RML.Views;
using Tango.PMR.ColorLab;

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

        private ObservablesContext _rmls_context;
        private ObservablesContext _active_context;

        private ObservableCollection<Rml> _rmls;
        public ObservableCollection<Rml> Rmls
        {
            get { return _rmls; }
            set { _rmls = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<MediaMaterial> _materials;
        public ObservableCollection<MediaMaterial> Materials
        {
            get { return _materials; }
            set { _materials = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<MediaColor> _colors;
        public ObservableCollection<MediaColor> Colors
        {
            get { return _colors; }
            set { _colors = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<MediaPurpos> _purposes;
        public ObservableCollection<MediaPurpos> Purposes
        {
            get { return _purposes; }
            set { _purposes = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<MediaCondition> _conditions;
        public ObservableCollection<MediaCondition> Conditions
        {
            get { return _conditions; }
            set { _conditions = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<LinearMassDensityUnit> _linearMassDensityUnits;
        public ObservableCollection<LinearMassDensityUnit> LinearMassDensityUnits
        {
            get { return _linearMassDensityUnits; }
            set { _linearMassDensityUnits = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<FiberShape> _fiberShapes;
        public ObservableCollection<FiberShape> FiberShapes
        {
            get { return _fiberShapes; }
            set { _fiberShapes = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<FiberSynth> _fiberSynths;
        public ObservableCollection<FiberSynth> FiberSynths
        {
            get { return _fiberSynths; }
            set { _fiberSynths = value; RaisePropertyChangedAuto(); }
        }

        private Rml _selectedRML;
        public Rml SelectedRML
        {
            get { return _selectedRML; }
            set { _selectedRML = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); }
        }

        private Rml _activeRML;
        public Rml ActiveRML
        {
            get { return _activeRML; }
            set { _activeRML = value; RaisePropertyChangedAuto(); }
        }

        private CalibrationDataViewVM _calibrationDataViewVM;
        public CalibrationDataViewVM CalibrationDataViewVM
        {
            get { return _calibrationDataViewVM; }
            set { _calibrationDataViewVM = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<LiquidTypesRml> _liquidTypesRmls;
        public ObservableCollection<LiquidTypesRml> LiquidTypesRmls
        {
            get { return _liquidTypesRmls; }
            set { _liquidTypesRmls = value; RaisePropertyChangedAuto(); }
        }

        private ProcessParametersTablesGroup _activeProcessParametersGroup;
        public ProcessParametersTablesGroup ActiveProcessParametersGroup
        {
            get { return _activeProcessParametersGroup; }
            set { _activeProcessParametersGroup = value; RaisePropertyChangedAuto(); }
        }

        private ICollectionView _activeProcessParametersTableView;
        public ICollectionView ActiveProcessParametersTableView
        {
            get { return _activeProcessParametersTableView; }
            set { _activeProcessParametersTableView = value; RaisePropertyChangedAuto(); }
        }


        /// <summary>
        /// Gets or sets the manage RML command.
        /// </summary>
        public RelayCommand ManageRmlCommand { get; set; }

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

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

        public RelayCommand AddProcessParametersTableCommand { get; set; }

        public RelayCommand<ProcessParametersTable> RemoveProcessParametersTableCommand { get; set; }

        public RelayCommand AddLiquidFactorCommand { get; set; }

        public RelayCommand<LiquidTypesRml> RemoveLiquidFactorCommand { get; set; }

        public RelayCommand CreateCalibrationDataExcelTemplateCommand { get; set; }

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

        public RelayCommand SaveCommand { get; set; }

        public MainViewVM(INotificationProvider notificationProvider)
        {
            _notification = notificationProvider;
            ManageRmlCommand = new RelayCommand(() => LoadActiveRML(SelectedRML.Guid), () => SelectedRML != null);
            RemoveRmlCommand = new RelayCommand(RemoveSelectedRml);
            AddRmlCommand = new RelayCommand(AddNewRml);
            BackToRmlsCommand = new RelayCommand(BackToRmls, () => IsFree);
            AddProcessParametersTableCommand = new RelayCommand(AddProcessParametersTable, () => IsFree);
            RemoveProcessParametersTableCommand = new RelayCommand<ProcessParametersTable>(RemoveProcessParametersTable, () => IsFree);
            AddLiquidFactorCommand = new RelayCommand(AddLiquidFactor, () => IsFree);
            RemoveLiquidFactorCommand = new RelayCommand<LiquidTypesRml>(RemoveLiquidFactor, () => IsFree);
            CreateCalibrationDataExcelTemplateCommand = new RelayCommand(CreateCalibrationDataExcelTemplate);
            SaveCommand = new RelayCommand(Save, () => IsFree);
        }

        public override void OnApplicationReady()
        {
            LoadRmls();
        }

        private async void LoadRmls()
        {
            if (_rmls_context != null) _rmls_context.Dispose();

            _rmls_context = ObservablesContext.CreateDefault();
            Rmls = await new RmlsCollectionBuilder(_rmls_context).Set().WithLiquidFactors().WithMediaProperties().BuildAsync();
        }

        private async void LoadActiveRML(String guid)
        {
            using (_notification.PushTaskItem("Loading RML..."))
            {
                IsFree = false;

                if (_active_context != null)
                {
                    _active_context.Dispose();
                }

                _active_context = ObservablesContext.CreateDefault();

                LoadRmlProperties();

                ActiveRML = await new RmlBuilder(_active_context)
                    .Set(guid)
                    .WithActiveParametersGroup()
                    .WithLiquidFactors()
                    .WithMediaProperties()
                    .BuildAsync();

                if (ActiveRML.ProcessParametersTablesGroups.ToList().Count == 0)
                {
                    if (!_notification.ShowQuestion("Could not find any process group for the selected RML. Would you like to create one?"))
                    {
                        _notification.ShowError("Cannot load an RML with no process group.");
                        IsFree = true;
                        return;
                    }
                    else
                    {
                        ProcessParametersTablesGroup group = new ProcessParametersTablesGroup();
                        group.Name = "Active Group";
                        group.Active = true;
                        group.ProcessParametersTables.Add(new ProcessParametersTable()
                        {
                            Name = "Process Table 1",
                        });

                        group.Rml = ActiveRML;

                        _active_context.ProcessParametersTablesGroups.Add(group);
                        _active_context.ProcessParametersTables.Add(group.ProcessParametersTables[0]);
                        await _active_context.SaveChangesAsync();
                        LoadActiveRML(ActiveRML.Guid);
                        return;
                    }
                }

                ActiveProcessParametersGroup = ActiveRML.ProcessParametersTablesGroups.ToList().FirstOrDefault();
                ActiveProcessParametersTableView = CollectionViewSource.GetDefaultView(ActiveProcessParametersGroup.ProcessParametersTables);
                ActiveProcessParametersTableView.SortDescriptions.Add(new SortDescription(nameof(ProcessParametersTable.TableIndex), ListSortDirection.Ascending));

                CalibrationDataViewVM = new CalibrationDataViewVM(_notification);
                LiquidTypesRmls = ActiveRML.LiquidTypesRmls;

                foreach (var liquidTypeRml in LiquidTypesRmls)
                {
                    CalibrationDataVM catVM = new CalibrationDataVM(liquidTypeRml.LiquidType);

                    if (liquidTypeRml.DefaultCatData != null)
                    {
                        catVM.CalibrationPoints = liquidTypeRml.GetCalibrationData().CalibrationPoints.Select(x => new CalibrationDataPointVM(x.X, x.Y)).ToObservableCollection();
                    }

                    CalibrationDataViewVM.LiquidsCalibrationData.Add(catVM);
                }


                View.NavigateTo(RmlNavigationView.RmlView);

                IsFree = true;
            }
        }

        private void LoadRmlProperties()
        {
            Materials = _active_context.MediaMaterials.ToObservableCollection();
            Colors = _active_context.MediaColors.ToObservableCollection();
            Purposes = _active_context.MediaPurposes.ToObservableCollection();
            Conditions = _active_context.MediaConditions.ToObservableCollection();
            LinearMassDensityUnits = _active_context.LinearMassDensityUnits.ToObservableCollection();
            FiberShapes = _active_context.FiberShapes.ToObservableCollection();
            FiberSynths = _active_context.FiberSynths.ToObservableCollection();
        }

        private async void AddNewRml()
        {
            var name = _notification.ShowTextInput("Please enter RML name", "Name");

            if (!String.IsNullOrWhiteSpace(name))
            {
                if (Rmls.ToList().Exists(x => x.Name == name))
                {
                    _notification.ShowError("The specified RML name already exists. Please select a different name.");
                    return;
                }

                using (_notification.PushTaskItem("Creating new RML..."))
                {
                    IsFree = false;

                    if (_active_context != null)
                    {
                        _active_context.Dispose();
                    }

                    _active_context = ObservablesContext.CreateDefault();

                    LoadRmlProperties();

                    Rml rml = new Rml();
                    rml.Name = name;
                    rml.Manufacturer = "Twine";
                    rml.Code = Rmls.Max(x => x.Code) + 1;
                    rml.MediaMaterial = Materials.FirstOrDefault();
                    rml.MediaColor = Colors.FirstOrDefault();
                    rml.MediaPurpose = Purposes.FirstOrDefault();
                    rml.MediaCondition = Conditions.FirstOrDefault();
                    rml.LinearMassDensityUnit = LinearMassDensityUnits.FirstOrDefault();
                    rml.FiberShape = FiberShapes.FirstOrDefault();
                    rml.FiberSynth = FiberSynths.FirstOrDefault();

                    ProcessParametersTablesGroup group = new ProcessParametersTablesGroup();
                    group.Name = "Active Group";
                    group.Active = true;
                    group.ProcessParametersTables.Add(new ProcessParametersTable()
                    {
                        Name = "Process Table 1",
                    });

                    group.Rml = rml;

                    _active_context.ProcessParametersTablesGroups.Add(group);
                    _active_context.ProcessParametersTables.Add(group.ProcessParametersTables[0]);
                    _active_context.Rmls.Add(rml);
                    await _active_context.SaveChangesAsync();
                    LoadActiveRML(rml.Guid);

                    IsFree = true;
                }
            }
        }

        private async void RemoveSelectedRml()
        {
            if (_notification.ShowQuestion("Removing the selected RML will result in the loss of all related process parameters and default calibration data. Are you sure you want to delete the selected RML?"))
            {
                IsFree = false;

                using (_notification.PushTaskItem("Removing RML..."))
                {
                    try
                    {
                        await SelectedRML.DeleteCascadeAsync(_rmls_context);
                        LoadRmls();
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, $"Error removing selected RML {SelectedRML.Name}.");
                        _notification.ShowError($"An error occurred while trying to remove the selected RML.\n{ex.Message}");
                    }
                }

                IsFree = true;
            }
        }

        private void AddProcessParametersTable()
        {
            var name = _notification.ShowTextInput("Enter table name", "Name");

            if (!String.IsNullOrWhiteSpace(name))
            {
                _active_context.ProcessParametersTables.Add(new ProcessParametersTable()
                {
                    ProcessParametersTablesGroup = ActiveProcessParametersGroup,
                    Name = name,
                    TableIndex = ActiveProcessParametersGroup.ProcessParametersTables.Max(x => x.TableIndex) + 1,
                });
            }
        }

        public void OnProcessParametersTableDropped(ProcessParametersTable dragged, ProcessParametersTable dropped)
        {
            if (dragged.TableIndex > dropped.TableIndex)
            {
                dragged.TableIndex = dropped.TableIndex - 1;
            }
            else
            {
                dragged.TableIndex = dropped.TableIndex + 1;
            }

            int index = 0;

            foreach (var table in ActiveProcessParametersGroup.ProcessParametersTables.OrderBy(x => x.TableIndex))
            {
                table.TableIndex = index++;
            }

            ActiveProcessParametersTableView.Refresh();
        }

        private void RemoveLiquidFactor(LiquidTypesRml liquidFactor)
        {
            if (_notification.ShowQuestion("Removing this liquid factor will remove the liquid type association with the RML and will drop the calibration data. Are you sure?"))
            {
                var catVM = CalibrationDataViewVM.LiquidsCalibrationData.SingleOrDefault(x => x.LiquidType == liquidFactor.LiquidType);
                CalibrationDataViewVM.LiquidsCalibrationData.Remove(catVM);
                _active_context.LiquidTypesRmls.Remove(liquidFactor);
            }
        }

        private void AddLiquidFactor()
        {
            AddLiquidFactorViewVM vm = new AddLiquidFactorViewVM(_active_context);
            _notification.ShowModalDialog<AddLiquidFactorViewVM, AddLiquidFactorView>(vm, (_) =>
            {
                if (LiquidTypesRmls.ToList().Exists(x => x.LiquidType == vm.SelectedLiquidType))
                {
                    _notification.ShowError("The selected liquid type is already associated with this RML.");
                    return;
                }

                LiquidTypesRml liquidFactor = new LiquidTypesRml()
                {
                    LiquidType = vm.SelectedLiquidType,
                    Rml = ActiveRML,
                };

                _active_context.LiquidTypesRmls.Add(liquidFactor);

                CalibrationDataVM catVM = new CalibrationDataVM(liquidFactor.LiquidType);

                CalibrationDataViewVM.LiquidsCalibrationData.Add(catVM);

            }, () => { });
        }

        private void RemoveProcessParametersTable(ProcessParametersTable processParametersTable)
        {
            if (ActiveProcessParametersGroup.ProcessParametersTables.Count == 1)
            {
                _notification.ShowError("The process group must contain at least one table.");
                return;
            }

            if (_notification.ShowQuestion("Are you sure you want to remove this process parameters table?"))
            {
                _active_context.ProcessParametersTables.Remove(processParametersTable);
            }
        }

        private void CreateCalibrationDataExcelTemplate()
        {
            SaveFileDialog dlg = new SaveFileDialog();
            try
            {
                dlg.Title = $"Create excel template file";
                dlg.Filter = "Excel Files|*.xlsx";
                dlg.DefaultExt = ".xlsx";
                dlg.FileName = "Calibration File Template";
                if (dlg.ShowDialog().Value)
                {
                    CalibrationHelper.CreateCalibrationDataExcelTemplate(dlg.FileName);
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error generating excel calibration template file " + dlg.FileName);
                _notification.ShowError("An error occurred while trying to generate the calibration file.");
            }
        }

        private async void Save()
        {
            IsFree = false;

            try
            {
                using (_notification.PushTaskItem("Saving RML..."))
                {
                    foreach (var calDataVM in CalibrationDataViewVM.LiquidsCalibrationData)
                    {
                        var liquidTypeRml = LiquidTypesRmls.SingleOrDefault(x => x.LiquidType == calDataVM.LiquidType);
                        CalibrationData calData = new CalibrationData();
                        calData.LiquidType = (PMR.ColorLab.LiquidType)liquidTypeRml.LiquidType.Code;
                        calData.CalibrationPoints.AddRange(calDataVM.CalibrationPoints.Select(x => new CalibrationPoint() { X = x.X, Y = x.Y }));
                        liquidTypeRml.PutCalibrationData(calData);
                    }

                    ActiveRML.LastUpdated = DateTime.UtcNow;

                    await _active_context.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, $"Error saving RML {ActiveRML.Name}");
                _notification.ShowError($"An error occurred while trying to save the current RML.\n{ex.Message}");
            }

            LoadActiveRML(ActiveRML.Guid);

            IsFree = true;
        }

        private void BackToRmls()
        {
            View.NavigateTo(RmlNavigationView.RmlsView);
            LoadRmls();
        }
    }
}