aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModels/MachineSetupViewVM.cs
blob: 1bd1e1eea8d4977eabc4b4e0175111b62502f4f0 (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
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core;
using Tango.Core.Commands;
using Tango.Core.Helpers;
using Tango.Integration.Operation;
using Tango.Logging;
using Tango.PMR.Connection;
using Tango.PPC.Common;
using Tango.PPC.Common.Application;
using Tango.PPC.Common.Connection;
using Tango.PPC.Common.MachineSetup;
using Tango.PPC.Common.Navigation;
using Tango.PPC.Common.OS;
using Tango.PPC.Common.Web;
using Tango.PPC.UI.ViewsContracts;
using Tango.Settings;
using Tango.SharedUI.Helpers;
using Tango.SQLExaminer;
using Tango.Transport.Adapters;
using Tango.Web;

namespace Tango.PPC.UI.ViewModels
{
    /// <summary>
    /// Represents the machine setup view ViewModel.
    /// </summary>
    /// <seealso cref="Tango.PPC.Common.PPCViewModel{Tango.PPC.UI.ViewsContracts.IMachineSetupView}" />
    public class MachineSetupViewVM : PPCViewModel<IMachineSetupView>
    {
        /// <summary>
        /// Represents the various machine setup view states.
        /// </summary>
        public enum MachineSetupStates
        {
            None,
            Working,
            Completed,
            Failed,
        }

        public enum MachineSetupView
        {
            WelcomeView,
            WiFiSelectionView,
            WiFiTestView,
            TimeZoneView,
            EnvironmentView,
            SetupWelcomeView,
            SetupProgressView,
            SetupCompletedView,
            SetupFailedView,
        }

        private MachineSetupResult _setup_result;
        private IOperationSystemManager _operationSystemManager;
        private IPPCApplicationManager _appManager;
        private PPCWebClient _ppcWebClient;

        #region Properties

        /// <summary>
        /// Gets or sets the machine setup manager.
        /// </summary>
        public IMachineSetupManager MachineSetupManager { get; set; }

        private String _serialNumber;
        /// <summary>
        /// Gets or sets the serial number.
        /// </summary>
        public String SerialNumber
        {
            get { return _serialNumber; }
            set { _serialNumber = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); }
        }

        private String _hostAddress;
        /// <summary>
        /// Gets or sets the host address.
        /// </summary>
        public String HostAddress
        {
            get { return _hostAddress; }
            set { _hostAddress = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); }
        }

        private String _log;
        /// <summary>
        /// Gets or sets the log.
        /// </summary>
        public String Log
        {
            get { return _log; }
            set { _log = value; RaisePropertyChangedAuto(); }
        }

        private MachineSetupStates _state;
        /// <summary>
        /// Gets or sets the state.
        /// </summary>
        public MachineSetupStates State
        {
            get { return _state; }
            set { _state = value; RaisePropertyChangedAuto(); InvalidateRelayCommands(); }
        }

        private String _failedError;
        /// <summary>
        /// Gets or sets the setup failed error.
        /// </summary>
        public String FailedError
        {
            get { return _failedError; }
            set { _failedError = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets or sets the available time zones.
        /// </summary>
        public List<TimeZoneInfo> TimeZones { get; set; }

        private TimeZoneInfo _selectedTimeZone;
        /// <summary>
        /// Gets or sets the selected time zone.
        /// </summary>
        public TimeZoneInfo SelectedTimeZone
        {
            get { return _selectedTimeZone; }
            set { _selectedTimeZone = value; RaisePropertyChangedAuto(); }
        }

        private DeploymentSlot _deploymentSlot;
        /// <summary>
        /// Gets or sets the deployment slot.
        /// </summary>
        public DeploymentSlot DeploymentSlot
        {
            get { return _deploymentSlot; }
            set { _deploymentSlot = value; RaisePropertyChangedAuto(); }
        }

        private MachineSetupView _currentView;
        public MachineSetupView CurrentView
        {
            get { return _currentView; }
            set { _currentView = value; RaisePropertyChangedAuto(); }
        }

        #endregion

        #region Commands

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

        /// <summary>
        /// Gets or sets the navigate to WiFi command.
        /// </summary>
        public RelayCommand NavigateToWiFiCommand { get; set; }

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

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

        /// <summary>
        /// Gets or sets the time zone selected command.
        /// </summary>
        public RelayCommand TimeZoneSelectedCommand { get; set; }

        /// <summary>
        /// Gets or sets the environment selected command.
        /// </summary>
        public RelayCommand EnvironmentSelectedCommand { get; set; }
        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="MachineSetupViewVM"/> class.
        /// </summary>
        /// <param name="applicationManager">The application manager.</param>
        /// <param name="machineSetupManager">The machine setup manager.</param>
        public MachineSetupViewVM(PPCWebClient ppcWebClient, IPPCApplicationManager applicationManager, IMachineSetupManager machineSetupManager, IOperationSystemManager operationSystemManager)
        {
            _ppcWebClient = ppcWebClient;
            _appManager = applicationManager;
            MachineSetupManager = machineSetupManager;

            DeploymentSlot = Settings.DeploymentSlot;

            SerialNumber = "";

            CompleteCommand = new RelayCommand(CompleteSetup, () => State == MachineSetupStates.Completed);

            applicationManager.SetupRequired += ApplicationManager_SetupRequired;

            NavigateToWiFiCommand = new RelayCommand(EnsureWiFi);

            InstallCommand = new RelayCommand(Install);
            RestartCommand = new RelayCommand(() => { NavigateTo(MachineSetupView.WelcomeView); });
            TimeZoneSelectedCommand = new RelayCommand(() => { NavigateTo(MachineSetupView.EnvironmentView); });
            EnvironmentSelectedCommand = new RelayCommand(() =>
            {
                NavigateTo(MachineSetupView.SetupWelcomeView);
                Settings.DeploymentSlot = DeploymentSlot;
                HostAddress = Settings.GetMachineServiceAddress();
                Settings.Save();
            });

            _operationSystemManager = operationSystemManager;

            TimeZones = _operationSystemManager.GetAvailableTimeZones().ToList();
            SelectedTimeZone = TimeZones.SingleOrDefault(x => x.ToString() == "(UTC+02:00) Jerusalem");
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handles the SetupRequired event of the ApplicationManager.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void ApplicationManager_SetupRequired(object sender, EventArgs e)
        {
            if (!LogManager.Categories.Contains(LogCategory.Debug))
            {
                LogManager.Categories.Add(LogCategory.Debug);
            }

            var logger = new SimpleStringLogger();
            logger.Categories.Remove(LogCategory.Debug);
            LogManager.RegisterLogger(logger);
            logger.LogReceived += Logger_LogReceived;

            LogManager.Log("SetupRequired event received. Navigating to MachineSetupView...");
            NavigationManager.NavigateTo(NavigationView.MachineSetupView);
        }


        private void Logger_LogReceived(object sender, LogItemBase e)
        {
            AppendLog(e.Message);
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Appends the log.
        /// </summary>
        /// <param name="msg">The MSG.</param>
        private void AppendLog(String msg)
        {
            if (msg != null && !msg.Contains("SQL Examiner"))
            {
                InvokeUI(() =>
                {
                    View.AppendLog(msg + Environment.NewLine);
                });
            }
        }

        /// <summary>
        /// Completes the setup.
        /// </summary>
        private void CompleteSetup()
        {
            String updater_exe = Path.Combine(_setup_result.UpdatePackagePath, "Tango.PPC.Updater.exe");

            LogManager.Log("Completing machine setup...");
            LogManager.Log($"Executing '{updater_exe}' with arguments '{PathHelper.GetStartupPath()}'...");
            Process.Start(updater_exe, PathHelper.GetStartupPath());
            LogManager.Log("Terminating application process!");
            _appManager.ShutDown();
        }

        /// <summary>
        /// Navigates to the specified view.
        /// </summary>
        /// <param name="view">The view.</param>
        private Task NavigateTo(MachineSetupView view)
        {
            CurrentView = view;
            return View.NavigateTo(view);
        }

        #endregion

        #region WiFi

        private async void EnsureWiFi()
        {
            await NavigateTo(MachineSetupView.WiFiTestView);

            await Task.Delay(2000);

            bool connected = await ConnectivityProvider.CheckInternetConnection();

            if (connected)
            {
                await NavigateTo(MachineSetupView.TimeZoneView);
            }
            else
            {
                await NavigateTo(MachineSetupView.WiFiSelectionView);
                await ConnectivityProvider.RefreshAvailableWiFiNetworks();

                ConnectivityProvider.ConnectionStateChanged += ConnectivityProvider_ConnectionStateChanged;
            }
        }

        private async void ConnectivityProvider_ConnectionStateChanged(object sender, Common.Connectivity.ConnectionStateEventArgs e)
        {
            if (e.IsConnected)
            {
                ConnectivityProvider.ConnectionStateChanged -= ConnectivityProvider_ConnectionStateChanged;
                await NavigateTo(MachineSetupView.WiFiTestView);
                await Task.Delay(5000);
                EnsureWiFi();
            }
        }

        #endregion

        #region Setup

        private async void Install()
        {
            await NavigateTo(MachineSetupView.SetupProgressView);

            LogManager.Log("Starting machine setup...");

            State = MachineSetupStates.Working;

            try
            {
                _ppcWebClient.Environment = DeploymentSlot;
                await _operationSystemManager.ChangeTimeZone(SelectedTimeZone);
                _setup_result = await MachineSetupManager.Setup(SerialNumber);
                State = MachineSetupStates.Completed;
                LogManager.Log("Machine setup completed.");
                await NavigateTo(MachineSetupView.SetupCompletedView);
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Machine setup failed.");
                FailedError = ex.FlattenMessage();
                State = MachineSetupStates.Failed;
                await NavigateTo(MachineSetupView.SetupFailedView);
            }
        }

        #endregion
    }
}