aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.Storage/ViewModels/MainViewVM.cs
blob: 90644cf1a92c9517f45fd95f6a7bca3e2c88f418 (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
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core.Commands;
using Tango.Core.DI;
using Tango.Core.IO;
using Tango.Integration.ExternalBridge;
using Tango.Integration.Storage;
using Tango.MachineStudio.Common;
using Tango.MachineStudio.Common.FirmwareUpgrade;
using Tango.MachineStudio.Common.Notifications;
using Tango.MachineStudio.Common.StudioApplication;
using Tango.MachineStudio.Storage.Models;

namespace Tango.MachineStudio.Storage.ViewModels
{
    public class MainViewVM : StudioViewModel
    {
        public event EventHandler CurrentFolderChanged;

        private IStudioApplicationManager _applicationManager;
        private INotificationProvider _notification;
        private IFirmwareUpgrader _firmwareUpgrader;
        private bool _machine_operator_changed = true;

        private StorageManager _storageManager;
        public StorageManager StorageManager
        {
            get { return _storageManager; }
            set { _storageManager = value; RaisePropertyChangedAuto(); }
        }

        private StorageItem _selectedStorageItem;
        public StorageItem SelectedStorageItem
        {
            get { return _selectedStorageItem; }
            set { _selectedStorageItem = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); }
        }

        private String _currentPath;
        public String CurrentPath
        {
            get { return _currentPath; }
            set { _currentPath = value; RaisePropertyChangedAuto(); }
        }

        public ObservableCollection<StorageFileHandlerModel> FileHandlers { get; set; }

        public RelayCommand BackCommand { get; set; }

        public RelayCommand RefreshCommand { get; set; }

        public RelayCommand GoCommand { get; set; }

        public RelayCommand<StorageFileHandlerModel> CancelFileHandlerCommand { get; set; }

        public RelayCommand<StorageFileHandlerModel> OpenFileHandlerCommand { get; set; }

        public RelayCommand<StorageFileHandlerModel> RemoveFileHandlerCommand { get; set; }

        public RelayCommand DownloadFileCommand { get; set; }

        public RelayCommand DeleteFileCommand { get; set; }

        public RelayCommand CreateFolderCommand { get; set; }

        public RelayCommand DeleteFolderCommand { get; set; }

        public RelayCommand UploadFileCommand { get; set; }

        public RelayCommand UploadVersionCommand { get; set; }

        public RelayCommand ValidateVersionCommand { get; set; }

        public RelayCommand ActivateVersionCommand { get; set; }

        public RelayCommand GenerateTfpCommand { get; set; }

        public MainViewVM()
        {

        }

        [TangoInject]
        public MainViewVM(IStudioApplicationManager applicationManager, INotificationProvider notificationProvider, IFirmwareUpgrader firmwareUpgrader)
        {
            _applicationManager = applicationManager;
            _notification = notificationProvider;
            _firmwareUpgrader = firmwareUpgrader;
            _applicationManager.ConnectedMachineChanged += _applicationManager_ConnectedMachineChanged;

            FileHandlers = new ObservableCollection<StorageFileHandlerModel>();

            GoCommand = new RelayCommand(() => NavigateToPath(CurrentPath), () => StorageManager != null);
            BackCommand = new RelayCommand(NavigateBack, () => StorageManager != null && StorageManager.CurrentFolder.Parent != null);
            CancelFileHandlerCommand = new RelayCommand<StorageFileHandlerModel>(CancelFileHandler);
            OpenFileHandlerCommand = new RelayCommand<StorageFileHandlerModel>(OpenFileHandler);
            RefreshCommand = new RelayCommand(Refresh, () => StorageManager != null);
            RemoveFileHandlerCommand = new RelayCommand<StorageFileHandlerModel>(RemoveFileHandler);
            DownloadFileCommand = new RelayCommand(DownloadFile, () => StorageManager != null && SelectedStorageItem != null && SelectedStorageItem is StorageFile);
            DeleteFileCommand = new RelayCommand(DeleteFile, () => StorageManager != null && SelectedStorageItem != null && SelectedStorageItem is StorageFile);
            CreateFolderCommand = new RelayCommand(CreateFolder, () => StorageManager != null && StorageManager.CurrentFolder != null);
            DeleteFolderCommand = new RelayCommand(DeleteFolder, () => StorageManager != null && SelectedStorageItem != null && SelectedStorageItem is StorageFolder);
            UploadFileCommand = new RelayCommand(UploadFile, () => StorageManager != null && StorageManager.CurrentFolder != null);
            UploadVersionCommand = new RelayCommand(UploadVersion, () => StorageManager != null && StorageManager.CurrentFolder != null);
            ValidateVersionCommand = new RelayCommand(ValidateVersion, () => StorageManager != null && StorageManager.CurrentFolder != null);
            ActivateVersionCommand = new RelayCommand(ActivateVersion, () => StorageManager != null && StorageManager.CurrentFolder != null);
            GenerateTfpCommand = new RelayCommand(GenerateTFP);
        }

        private void UploadFile()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Selected a file to upload";
            if (dlg.ShowDialog().Value)
            {
                UploadFile(dlg.FileName);
            }
        }

        private async void DeleteFolder()
        {
            if (SelectedStorageItem == null) return;

            if (_notification.ShowQuestion("Are you sure you want to delete the selected folder?"))
            {
                try
                {
                    IsFree = false;
                    await StorageManager.DeleteItem(SelectedStorageItem);
                    Refresh();
                }
                catch (Exception ex)
                {
                    _notification.ShowError($"Error deleting the selected folder.\n{ex.Message}");
                }

                IsFree = true;
            }
        }

        private async void CreateFolder()
        {
            try
            {
                var name = _notification.ShowTextInput("Enter Folder Name", "");

                if (!String.IsNullOrWhiteSpace(name))
                {
                    IsFree = false;
                    await StorageManager.CreateFolder(Path.Combine(StorageManager.CurrentPath, name));
                    Refresh();
                }
            }
            catch (Exception ex)
            {
                _notification.ShowError($"Error creating the new folder.\n{ex.Message}");
            }

            IsFree = true;
        }

        private async void DeleteFile()
        {
            if (SelectedStorageItem == null) return;

            if (_notification.ShowQuestion("Are you sure you want to delete the selected file?"))
            {
                try
                {
                    IsFree = false;
                    await StorageManager.DeleteItem(SelectedStorageItem);
                    Refresh();
                }
                catch (Exception ex)
                {
                    _notification.ShowError($"Error deleting the selected file.\n{ex.Message}");
                }

                IsFree = true;
            }
        }

        private void DownloadFile()
        {
            DownloadStorageItem(SelectedStorageItem as StorageFile);
        }

        private void OpenFileHandler(StorageFileHandlerModel handler)
        {
            ShowInExplorer(handler.FilePath);
        }

        private async void CancelFileHandler(StorageFileHandlerModel handler)
        {
            await handler.Handler.Cancel();
        }

        private void _applicationManager_ConnectedMachineChanged(object sender, IExternalBridgeClient e)
        {
            _machine_operator_changed = true;

            if (IsVisible)
            {
                Initialize();
            }
        }

        public override void OnApplicationReady()
        {

        }

        public override void OnNavigatedTo()
        {
            base.OnNavigatedTo();

            if (_machine_operator_changed)
            {
                _machine_operator_changed = false;
                Initialize();
            }
        }

        private async void NavigateToPath(String path, bool raiseEvent = true)
        {
            IsFree = false;

            try
            {
                await StorageManager.GetFolder(path);
                CurrentPath = StorageManager.CurrentPath;

                if (raiseEvent)
                {
                    CurrentFolderChanged?.Invoke(this, new EventArgs());
                }
            }
            catch (Exception ex)
            {
                _notification.ShowError($"Error navigating to the specified path.\n{ex.Message}");
            }

            IsFree = true;

            InvalidateRelayCommands();
        }

        private async void Initialize()
        {
            if (_applicationManager.ConnectedMachine != null)
            {
                try
                {
                    StorageManager = _applicationManager.ConnectedMachine.CreateStorageManager();
                    await StorageManager.GetStorageDrive();
                    await StorageManager.GetRootFolder();
                    CurrentPath = StorageManager.StorageDrive.Root;
                }
                catch (Exception ex)
                {
                    _notification.ShowError($"An error occurred while trying to initialize the storage manager.\n{ex.Message}");
                }

                InvalidateRelayCommands();
            }
        }

        public void OnStorageItemDoubleClicked(StorageItem storageItem)
        {
            if (storageItem is StorageFolder && storageItem != null)
            {
                NavigateToPath(storageItem.Path);
            }
            else
            {
                DownloadStorageItem(storageItem as StorageFile);
            }
        }

        private void NavigateBack()
        {
            NavigateToPath(StorageManager.CurrentFolder.Parent);
        }

        private void Refresh()
        {
            NavigateToPath(StorageManager.CurrentFolder.Path, false);
        }

        private async void DownloadStorageItem(StorageFile storageFile)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Title = "Select download location";
            dlg.DefaultExt = Path.GetExtension(storageFile.Path);
            dlg.FileName = storageFile.Name;
            if (dlg.ShowDialog().Value)
            {
                FileStream fs = new FileStream(dlg.FileName, FileMode.Create);
                var handler = await StorageManager.DownloadFile(storageFile, fs);
                handler.Completed += (_, __) =>
                {
                    fs.Dispose();
                };

                handler.Canceled += (_, __) =>
                {
                    fs.Dispose();
                    File.Delete(dlg.FileName);
                };

                handler.Failed += (_, __) =>
                {
                    fs.Dispose();
                    File.Delete(dlg.FileName);
                };

                FileHandlers.Insert(0, new StorageFileHandlerModel(handler, dlg.FileName, StorageFileHandlerType.Download));
            }
        }

        private async void UploadFile(String path)
        {
            FileStream fs = new FileStream(path, FileMode.Open);
            var handler = await StorageManager.UploadFile(Path.Combine(StorageManager.CurrentPath, Path.GetFileName(path)), fs);
            handler.Completed += (_, __) =>
            {
                fs.Dispose();
            };

            handler.Canceled += (_, __) =>
            {
                fs.Dispose();
            };

            handler.Failed += (_, __) =>
            {
                fs.Dispose();
            };

            FileHandlers.Insert(0, new StorageFileHandlerModel(handler, path, StorageFileHandlerType.Upload));
        }

        /// <summary>
        /// Shows the file in explorer.
        /// </summary>
        /// <param name="path">Name of the file/folder.</param>
        public static void ShowInExplorer(String path)
        {
            Process.Start("explorer.exe", string.Format("/select,\"{0}\"", path));
        }

        private void RemoveFileHandler(StorageFileHandlerModel handler)
        {
            if (handler.Handler.Status == StorageFileHandlerStatus.Active)
            {
                if (_notification.ShowQuestion("Are you sure you want to cancel this file operation?"))
                {
                    handler.Handler.Cancel();
                    FileHandlers.Remove(handler);
                }
            }
            else
            {
                FileHandlers.Remove(handler);
            }
        }

        private void UploadVersion()
        {
            _firmwareUpgrader.InvokeUpgradeUI();
        }

        private async void ValidateVersion()
        {
            using (_notification.PushTaskItem("Validating firmware version..."))
            {
                try
                {
                    await _applicationManager.ConnectedMachine.ValidateFirmwareVersion(StorageManager.CurrentPath);
                    _notification.ShowInfo($"Version validated successfully!");
                }
                catch (Exception ex)
                {
                    _notification.ShowError($"Error validating firmware version.\n{ex.FlattenMessage()}");
                }
            }
        }

        private async void ActivateVersion()
        {
            using (_notification.PushTaskItem("Activating firmware version..."))
            {
                try
                {
                    await _applicationManager.ConnectedMachine.ActivateFirmwareVersion(StorageManager.CurrentPath);
                    _notification.ShowInfo($"Version activated successfully!");
                }
                catch (Exception ex)
                {
                    _notification.ShowError($"Error activating firmware version.\n{ex.FlattenMessage()}");
                }
            }
        }

        private void GenerateTFP()
        {
            Tango.FirmwarePackageGenerator.MainWindow fWindow = new FirmwarePackageGenerator.MainWindow();
            fWindow.Topmost = true;
            fWindow.Show();
            _applicationManager.RegisterOpenedWindow(fWindow);
        }
    }
}