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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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DWSIM.Interfaces;
using DWSIM.Simulate365.FormFactories;
using DWSIM.Simulate365.Models;
using DWSIM.Simulate365.Services;
using DWSIM.UI.Web.Settings;
using Newtonsoft.Json;
using DWSIM.ExtensionMethods;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using System.Threading;
using Timer = System.Windows.Forms.Timer;

namespace DWSIM.ProFeatures
{

    public partial class FormPortal : UserControl
    {
        private bool IsLoadingLicenseInfo = false;
        public IAnalyticsProvider AnalyticsProvider;
        private int TrialLicenseCreatedMessageCount = 0;
        private bool FileSavingInProgress = false;
        private Timer Timer1 = new Timer() { Interval = 5000 };
        public IFlowsheet fsheet;
        public string featurename = "";

        private List<string> TrialLicenseCreatedMessages = new List<string>() { "Assigning DWSIM Pro license...", "Setting up the virtual licensing environment...", "Finalizing setup..." };

        public FormPortal()
        {
            InitializeComponent();

            FileManagementService.GetInstance().OnFileSavedToDashboard += FileManagementService_FileSavedToDashboard;
            UserService.GetInstance().OnUserLoggedIn += UserService_OnUserLoggedIn;

            Disposed += OnDispose;
        }
        public void SetFlowsheet(IFlowsheet fs)
        {
            fsheet = fs;
        }

        private void UserService_OnUserLoggedIn(object sender, EventArgs e)
        {
            var isLoggedIn = UserService.GetInstance()._IsLoggedIn();
            if (isLoggedIn)
            {
                OnInitialize();
            }
        }

        private void FormPortal_Load(object sender, EventArgs e)
        {

        }

        private void OnDispose(object sender, EventArgs e)
        {
            try
            {
                UserService.GetInstance().OnUserLoggedIn -= UserService_OnUserLoggedIn;
                FileManagementService.GetInstance().OnFileSavedToDashboard -= FileManagementService_FileSavedToDashboard;
            }
            catch (Exception)
            {


            }

        }

        public async Task OnInitialize()
        {
            // Debugger.Launch();
            var isLoggedIn = UserService.GetInstance()._IsLoggedIn();
            if (!isLoggedIn)
            {
                notLoggedInPanel.Visible = true;
                return;
            }
            else
            {
                notLoggedInPanel.Visible = false;
                LoadingPanel.Visible = true;
            }
            StatusMessage.Text = "Checking for DWSIM Pro license...";
            var licenseInfo = await GetLicenseInfo();
            if (licenseInfo is not null)
            {
                if (licenseInfo.hasExistingLicense.HasValue & licenseInfo.hasExistingLicense.Value)
                {
                    AnalyticsProvider?.RegisterEvent("Portal Window 2: License Eligible For Trial", featurename, null);
                    SaveFlowsheet();
                }
                else if (licenseInfo.notEligibleForTrial.HasValue & licenseInfo.notEligibleForTrial.Value)
                {
                    AnalyticsProvider?.RegisterEvent("Portal Window 2: License Not Eligible For Trial", featurename, null);
                    LoadingPanel.Visible = false;
                    NoLicensePanel.Visible = true;
                }
                else if ((licenseInfo.trialLicenseCreated & licenseInfo.trialLicenseCreated.Value) == true)
                {
                    AnalyticsProvider?.RegisterEvent("Portal Window 2: Trial License Created Successfully", featurename, null);
                    TrialLicenseCreatedLogic();
                }

            }
        }

        private void TrialLicenseCreatedLogic()
        {
            Timer1.Tick += (_, __) => Timer1_Tick();
            Timer1.Start();
        }
        private void Timer1_Tick()
        {
            if (TrialLicenseCreatedMessageCount + 1 < TrialLicenseCreatedMessages.Count)
            {
                TrialLicenseCreatedMessageCount += 1;
                this.UIThread(() =>
                {
                    StatusMessage.Text = TrialLicenseCreatedMessages[TrialLicenseCreatedMessageCount];
                });
            }
            else
            {
                Timer1.Stop();
                SaveFlowsheet();
            }
        }

        private void FileManagementService_FileSavedToDashboard(object sender, EventArgs e)
        {
            saveToDashboardBtn.Visible = false;
            SaveStartupActionAndRedirect();

        }
        private async void SaveStartupActionAndRedirect()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(SaveStartupActionAndRedirect));
            }
            else
            {
                if (FileSavingInProgress)
                {
                    FileSavingInProgress = false;
                    bool actionSaved = await SaveDwsimProStartupAction();
                    ShowSuccessPanel();
                }
            }
        }

        private static SemaphoreSlim __licenseRequestLock = new SemaphoreSlim(1);

        private async Task<LicenseResponseModel> GetLicenseInfo()
        {
            await __licenseRequestLock.WaitAsync();

            string url = $"{DashboardSettings.DashboardServiceUrl}/api/licensing/license-info";
            var token = UserService.GetInstance().GetUserToken();
            try
            {
                IsLoadingLicenseInfo = true;
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var content = new StringContent(JsonConvert.SerializeObject(new { source = "dwsim-os" }), Encoding.UTF8, "application/json");
                var response = await httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    // Read response content as string
                    string responseBody = await response.Content.ReadAsStringAsync();
                    var licensingResponse = JsonConvert.DeserializeObject<LicenseResponseModel>(responseBody);

                    AnalyticsProvider?.RegisterEvent("Portal Window 2: License Check Successful", featurename, null);
                    return licensingResponse;
                }
                else
                {
                    AnalyticsProvider?.RegisterEvent("Portal Window 2: License Check Failed", response.ReasonPhrase, null);
                    MessageBox.Show("Error: " + response.StatusCode.ToString() + " - " + response.ReasonPhrase);
                }
            }
            catch (Exception ex)
            {
                AnalyticsProvider?.RegisterEvent("Portal Window 2: License Check Failed", ex.Message, null);
                MessageBox.Show("An error occurred: " + ex.Message);
            }
            finally
            {
                __licenseRequestLock.Release();
                IsLoadingLicenseInfo = false;
            }

            return null;
        }

        private void ShowSuccessPanel()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(ShowSuccessPanel));
            }
            else
            {
                AnalyticsProvider?.RegisterEvent("Portal Window 2: Open-Source to Pro Workflow Finished Successfully", featurename, null);
                LoadingPanel.Visible = false;
                SuccessPanel.Visible = true;
            }
        }

        private void SaveFlowsheet()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(SaveFlowsheet));
            }
            else
            {
                if (fsheet != null)
                {
                    StatusMessage.Text = "To continue to DWSIM Pro, you must save your file to your Simulate 365 Dashboard.";
                    this.saveToDashboardBtn.Visible = true;
                }
                else
                {
                    ShowSuccessPanel();
                }
            }




        }
        private async Task<bool> SaveDwsimProStartupAction()
        {
            try
            {
                S365File currentFlowsheet = (S365File)fsheet.FlowsheetOptions.VirtualFile;

                if (string.IsNullOrWhiteSpace(currentFlowsheet?.FileUniqueIdentifier))
                {
                    return false;
                }

                var loadFileAction = new DWSIMProStartupAction()
                {
                    Action = "load-flowsheet",
                    Data = new Dictionary<string, string>() {
                        { "fileUniqueIdentifier", currentFlowsheet.FileUniqueIdentifier },
                        {"filename",currentFlowsheet.Filename }
                    }
                };
                var postData = new CreateStartupActionPostModel { Actions = new List<DWSIMProStartupAction> { loadFileAction } };
                string jsonContent = JsonConvert.SerializeObject(postData);
                var token = UserService.GetInstance().GetUserToken();
                string url = $"{DashboardSettings.DashboardServiceUrl}/api/dwsim-pro-startup-actions";
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");


                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                var response = await httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }

        }

        private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AnalyticsProvider?.RegisterEvent("Portal Window 2: User Clicked 'Go to Shop'", featurename, null);
            Process.Start("https://simulate365.com/shop/");
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AnalyticsProvider?.RegisterEvent("Portal Window 2: User Clicked 'Login'", featurename, null);
            var loginForm = new LoginForm(true);
            loginForm.ShowDialog();
        }

        private void openInDefaultBrowserLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AnalyticsProvider?.RegisterEvent("Portal Window 2: User Clicked 'Open Browser (Normal)'", featurename, null);
            Process.Start("https://vm.simulate365.com");
        }

        private void openInIncognitoLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

        }

        private string GetDefaultBrowserLocation()
        {
            var progId = GetStandardBrowserProgId();
            using var command = Registry.ClassesRoot.OpenSubKey($"{progId}\\shell\\open\\command");
            var runCommand = command?.GetValue(null) as string;
            if (!string.IsNullOrWhiteSpace(runCommand))
            {
                var splitCommand = Regex.Split(runCommand, ".exe");
                var browserLocation = splitCommand[0].Replace("\"", "");
                return browserLocation + ".exe";

            }
            return string.Empty;
        }


        private static string GetStandardBrowserProgId()
        {
            string userChoice = @"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice";
            string progId;
            using (RegistryKey userChoiceKey = Registry.CurrentUser.OpenSubKey(userChoice))
            {
                if (userChoiceKey == null)
                {
                    return string.Empty;
                }
                object progIdValue = userChoiceKey.GetValue("Progid");
                if (progIdValue == null)
                {
                    return string.Empty;
                }
                progId = progIdValue.ToString();
                return progId;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AnalyticsProvider?.RegisterEvent("Portal Window 2: User Clicked 'Go to Shop'", featurename, null);
            Process.Start("https://simulate365.com/shop/");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            AnalyticsProvider?.RegisterEvent("Portal Window 2: User Clicked 'Open Browser in Private Mode'", featurename, null);
            string privateModeParam = string.Empty;
            var url = "https://vm.simulate365.com";
            var browserProgId = GetStandardBrowserProgId()?.ToLower();
            if (string.IsNullOrWhiteSpace(browserProgId))
            {
                Process.Start(url);
            }
            else
            {

                if (browserProgId.Contains("firefox"))
                {
                    privateModeParam = " --private-window";
                }
                else if (browserProgId.Contains("ie.http"))
                {
                    privateModeParam = " -private";
                }
                else if (browserProgId.Contains("chrome") || browserProgId.Contains("opera"))
                {
                    privateModeParam = " /incognito";
                }
                else if (browserProgId.Contains("edge"))
                {
                    privateModeParam = " -inprivate";
                }

                var browserLocation = GetDefaultBrowserLocation();


                Process.Start(browserLocation, $"{privateModeParam} {url}");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            AnalyticsProvider?.RegisterEvent("Portal Window 2: User Clicked 'Open Browser (Normal)'", featurename, null);
            Process.Start("https://vm.simulate365.com");
        }

        private void saveToDashboardBtn_Click(object sender, EventArgs e)
        {
            AnalyticsProvider?.RegisterEvent("Portal Window 2: User Clicked 'Save to Dashboard'", featurename, null);
            this.FileSavingInProgress = true;
            // We fire event to save file and continue on FileManagementService_FileSavedToDashboard
            FileManagementService.GetInstance().SaveFileToDashboard();
        }

        private void registerLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("https://simulate365.com/registration/");
        }
    }
}