aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/FSE/Tango.FSE.UI/ViewModels/LayoutViewVM.cs
blob: c7b52df81391e3395be3b90e956c7471e7db2967 (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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.BL.Enumerations;
using Tango.BL.Helpers;
using Tango.Core.Commands;
using Tango.Core.DI;
using Tango.Core.IO;
using Tango.Core.Threading;
using Tango.CSV;
using Tango.FSE.Common;
using Tango.FSE.Common.HotFolder;
using Tango.FSE.Common.Navigation;
using Tango.FSE.Common.Notifications;
using Tango.FSE.Common.RemoteJobUpload;
using Tango.FSE.UI.Dialogs;
using Tango.FSE.UI.Panes;
using Tango.FSE.UI.Views;
using Tango.Integration.ExternalBridge;
using Tango.PPC.Shared.Statistics;
using Tango.SharedUI.Helpers;
using Tango.Transport;
using static Tango.BL.Helpers.SegmentsCsvHelper;

namespace Tango.FSE.UI.ViewModels
{
    /// <summary>
    /// Represents the application main layout view model.
    /// </summary>
    /// <seealso cref="Tango.FSE.Common.FSEViewModel" />
    public class LayoutViewVM : FSEViewModel
    {
        private ActionTimer _transportOutActionTimer;
        private ActionTimer _transportInActionTimer;

        #region Properties

        private bool _isConnectionPaneOpened;
        /// <summary>
        /// Gets or sets a value indicating whether the machine connection pane is opened.
        /// </summary>
        public bool IsConnectionPaneOpened
        {
            get { return _isConnectionPaneOpened; }
            set { _isConnectionPaneOpened = value; RaisePropertyChangedAuto(); OnConnectionPaneToggleChanged(); }
        }

        private MachineConnectionPaneVM _connectionPaneVM;
        /// <summary>
        /// Gets or sets the machine connection pane view model.
        /// </summary>
        public MachineConnectionPaneVM ConnectionPaneVM
        {
            get { return _connectionPaneVM; }
            set { _connectionPaneVM = value; RaisePropertyChangedAuto(); }
        }

        private ConnectedMachinePaneVM _connectedMachinePaneVM;
        /// <summary>
        /// Gets or sets the connected machine pane view model.
        /// </summary>
        public ConnectedMachinePaneVM ConnectedMachinePaneVM
        {
            get { return _connectedMachinePaneVM; }
            set { _connectedMachinePaneVM = value; RaisePropertyChangedAuto(); }
        }

        private LogViewerPaneVM _logViewPaneVM;
        /// <summary>
        /// Gets or sets the log viewer pane view model.
        /// </summary>
        public LogViewerPaneVM LogViewerPaneVM
        {
            get { return _logViewPaneVM; }
            set { _logViewPaneVM = value; RaisePropertyChangedAuto(); }
        }

        private bool _isMenuOpened;
        /// <summary>
        /// Gets or sets a value indicating whether the main menu is opened.
        /// </summary>
        public bool IsMenuOpened
        {
            get { return _isMenuOpened; }
            set { _isMenuOpened = value; RaisePropertyChangedAuto(); }
        }

        private bool _isLogsOpened;
        /// <summary>
        /// Gets or sets a value indicating whether the log viewer is opened.
        /// </summary>
        public bool IsLogsOpened
        {
            get { return _isLogsOpened; }
            set { _isLogsOpened = value; RaisePropertyChangedAuto(); }
        }

        private bool _transportOut;
        /// <summary>
        /// Transport out on/off.
        /// </summary>
        public bool TransportOut
        {
            get { return _transportOut; }
            set { _transportOut = value; RaisePropertyChanged(nameof(TransportOut)); }
        }

        private bool _transportIn;
        /// <summary>
        /// Transport in on/off.
        /// </summary>
        public bool TransportIn
        {
            get { return _transportIn; }
            set { _transportIn = value; RaisePropertyChanged(nameof(TransportIn)); }
        }

        [TangoInject]
        public IHotFolderService HotFolderService { get; set; }

        [TangoInject]
        public IRemoteJobUploadProvider RemoteJobUploadProvider { get; set; }

        #endregion

        #region Commands

        /// <summary>
        /// Toggles the connection pane visibility.
        /// </summary>
        public RelayCommand ToggleConnectionPaneCommand { get; set; }

        /// <summary>
        /// Logs outs the current user.
        /// </summary>
        public RelayCommand LogoutCommand { get; set; }

        /// <summary>
        /// Opens the bug report dialog.
        /// </summary>
        public RelayCommand ReportIssueCommand { get; set; }

        /// <summary>
        /// Navigates to the events view.
        /// </summary>
        public RelayCommand NavigateToEventsCommand { get; set; }

        /// <summary>
        /// Navigates to the home view.
        /// </summary>
        public RelayCommand NavigateHomeCommand { get; set; }

        /// <summary>
        /// Opens the hot folder configuration dialog.
        /// </summary>
        public RelayCommand ConfigureHotFolderCommand { get; set; }

        /// <summary>
        /// Opens the job upload dialog.
        /// </summary>
        public RelayCommand UploadJobCommand { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="LayoutViewVM"/> class.
        /// </summary>
        public LayoutViewVM()
        {
            ToggleConnectionPaneCommand = new RelayCommand(() => IsConnectionPaneOpened = !IsConnectionPaneOpened);
            ConnectionPaneVM = new MachineConnectionPaneVM();
            ConnectionPaneVM.MachineSelected += ConnectionPaneVM_MachineSelected;

            ConnectedMachinePaneVM = new ConnectedMachinePaneVM();
            ConnectedMachinePaneVM.DisconnectedFromMachine += ConnectedMachinePaneVM_DisconnectedFromMachine;

            LogViewerPaneVM = new LogViewerPaneVM();

            LogoutCommand = new RelayCommand(Logout);

            _transportOutActionTimer = new ActionTimer(TimeSpan.FromMilliseconds(50));
            _transportInActionTimer = new ActionTimer(TimeSpan.FromMilliseconds(50));

            ReportIssueCommand = new RelayCommand(OpenBugReportDialog);

            NavigateToEventsCommand = new RelayCommand(NavigateToEvents);
            NavigateHomeCommand = new RelayCommand(NavigateHome);
            ConfigureHotFolderCommand = new RelayCommand(ConfigureHotFolder);

            UploadJobCommand = new RelayCommand(UploadJob);
        }

        #endregion

        #region Machine Operator Event Handlers

        private void MachineProvider_MachineDisconnected(object sender, Common.Connection.MachineDisconnectedEventArgs e)
        {
            if (e.MachineOperator.Adapter != null)
            {
                e.MachineOperator.Adapter.PropertyChanged -= Adapter_PropertyChanged;
            }
        }

        private void MachineProvider_MachineConnected(object sender, Common.Connection.MachineConnectedEventArgs e)
        {
            e.MachineOperator.Adapter.PropertyChanged -= Adapter_PropertyChanged;
            e.MachineOperator.Adapter.PropertyChanged += Adapter_PropertyChanged;
        }

        private void Adapter_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(ITransportAdapter.TotalBytesSent))
            {
                TransportOut = true;
                _transportOutActionTimer.ResetReplace(() => TransportOut = false);
            }
            else if (e.PropertyName == nameof(ITransportAdapter.TotalBytesReceived))
            {
                TransportIn = true;
                _transportInActionTimer.ResetReplace(() => TransportIn = false);
            }
        }

        #endregion

        #region Connected Machine Pane Event Handlers

        private async void ConnectedMachinePaneVM_DisconnectedFromMachine(object sender, EventArgs e)
        {
            IsConnectionPaneOpened = false;

            try
            {
                await MachineProvider.DisconnectMachine();
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error disconnecting from machine.");
                await NotificationProvider.ShowError("Error occurred while trying to disconnect from the machine.");
            }
        }

        #endregion

        #region Machine Connection Pane Event Handlers

        private async void ConnectionPaneVM_MachineSelected(object sender, IExternalBridgeClient machine)
        {
            IsConnectionPaneOpened = false;

            LogManager.Log($"Machine '{machine.SerialNumber}' selected for connection by user.");

            try
            {
                if (await MachineProvider.ConnectToMachine(machine))
                {
                    NotificationProvider.PushSnackbarItem(MessageType.Success, "Machine successfully connected", true, $"{MachineProvider.Machine.SerialNumber}, {MachineProvider.Machine.Name}", TimeSpan.FromSeconds(5));
                }
            }
            catch (Exception ex)
            {
                await NotificationProvider.ShowError($"Error occurred while trying to connect to the specified machine.\n{ex.FlattenMessage()}");
                LogManager.Log(ex, $"Error connecting to machine '{machine.SerialNumber}'.");
            }
        }

        #endregion

        #region Override Methods

        public override void OnApplicationStarted()
        {
            MachineProvider.MachineDisconnected += MachineProvider_MachineDisconnected;
            MachineProvider.MachineConnected += MachineProvider_MachineConnected;
        }

        public override void OnNavigatedTo()
        {
            base.OnNavigatedTo();
            this.SetFocus(nameof(ToggleConnectionPaneCommand));
        }

        public override async Task<bool> OnApplicationLogout()
        {
            if (MachineProvider.IsConnected)
            {
                if (await NotificationProvider.ShowWarningQuestion("The current machine connection will be automatically closed.\nAre you sure you want to log out?"))
                {
                    await MachineProvider.DisconnectMachine();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return true;
            }
        }

        #endregion

        #region Private Methods

        private void OnConnectionPaneToggleChanged()
        {
            if (!MachineProvider.IsConnected)
            {
                if (IsConnectionPaneOpened)
                {
                    try
                    {
                        ConnectionPaneVM.Start();
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error while trying to initialize machine scanning.");
                        NotificationProvider.ShowError($"Error occurred while trying to initialize machine scanning.\n{ex.FlattenMessage()}");
                        _isConnectionPaneOpened = false;
                        RaisePropertyChanged(nameof(IsConnectionPaneOpened));
                    }
                }
                else
                {
                    try
                    {
                        ConnectionPaneVM.Stop();
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error while stopping machine scanning.");
                    }
                }
            }
        }

        private void Logout()
        {
            LogManager.Log("Logout command pressed by user.");
            AuthenticationProvider.LogOut();
        }

        private void OpenBugReportDialog()
        {
            BugReporter.ShowBugReportDialog();
        }

        private void NavigateToEvents()
        {
            NavigationManager.NavigateTo<InternalModule>(nameof(EventsView));
        }

        private void NavigateHome()
        {
            NavigationManager.NavigateTo(NavigationView.Home);
        }

        private async void ConfigureHotFolder()
        {
            await NotificationProvider.ShowDialog<HotFolderConfigurationViewVM>();
        }

        private async void UploadJob()
        {
            RequiredFiltersData data = null;
            try
            {
                using (NotificationProvider.PushTaskItem("Preparing job upload requirements..."))
                {
                    await Task.Delay(1500);
                    data = await StatisticsProvider.GetRequiredFiltersData();
                }
            }
            catch (Exception ex)
            {
                await NotificationProvider.ShowError($"Error preparing job upload requirements.\n{ex.FlattenMessage()}");
                return;
            }

            var lastSelectedRml = data.Rmls.FirstOrDefault(x => x.Guid == Settings.LastJobUploadThreadGuid);
            if (lastSelectedRml == null) lastSelectedRml = data.Rmls.FirstOrDefault();
            var vm = await NotificationProvider.ShowDialog(new JobUploadViewVM(MachineProvider) { Rmls = data.Rmls, SelectedRML = lastSelectedRml });

            if (vm.DialogResult)
            {
                TemporaryFile tmpFile = TemporaryManager.CreateImaginaryFile(".csv");

                try
                {
                    Settings.LastJobUploadThreadGuid = vm.SelectedRML.Guid;
                    Settings.Save();

                    CsvDynamicWriter csv = new CsvDynamicWriter();

                    int cIndex = 0;

                    csv.Write(1, "Index", 0, cIndex++);
                    csv.Write(vm.SelectedRML.Name, "ThreadName", "", cIndex++);
                    csv.Write(vm.Length, "Length", 0, cIndex++);
                    csv.Write(ColorSpaces.Volume, "ColorSpace", ColorSpaces.Volume, cIndex++);
                    foreach (var liquidVolume in vm.Volumes)
                    {
                        if (liquidVolume.Volume > 0)
                        {
                            csv.Write(liquidVolume.Volume, liquidVolume.LiquidType.DisplayName, 0, cIndex);
                        }
                    }

                    csv.Save(tmpFile);
                }
                catch (Exception ex)
                {
                    await NotificationProvider.ShowError($"Error creating job upload file.\n{ex.FlattenMessage()}");
                    tmpFile.Delete();
                    return;
                }

                SnackbarItem progress = null;

                try
                {
                    progress = NotificationProvider.PushProgressSnackbar("Job Upload", $"Uploading job '{vm.Name}'...");
                    await Task.Delay(1500);
                    await RemoteJobUploadProvider.UploadJob(tmpFile, PPC.Shared.RemoteJobUpload.RemoteJobUploadType.CSV, vm.Name);

                    progress.ProgressCompleted("Job uploaded successfully", TimeSpan.FromSeconds(2));
                }
                catch (Exception ex)
                {
                    progress.ProgressFailed($"Error uploading job.\n{ex.Message}");
                    return;
                }
            }

        }

        #endregion
    }
}