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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
using DWSIM.ExtensionMethods;
using DWSIM.GlobalSettings;
using DWSIM.Interfaces;
using ICSharpCode.SharpZipLib.Zip;
using iTextSharp.text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using unvell.ReoGrid;
using unvell.ReoGrid.DataFormat;
using unvell.ReoGrid.Formula;
using static DWSIM.Interfaces.Enums.Scripts;

namespace DWSIM.Automation
{
    [Guid("474a8e52-0b3e-48cb-a3bb-aae60f843578"), ClassInterface(ClassInterfaceType.None)]
    [ComVisible(true)]
    public class Flowsheet2 : FlowsheetBase.FlowsheetBase
    {
        private Action<string, IFlowsheet.MessageType> listeningaction;

        private Action updateUIaction;

        private IWorkbook Spreadsheet;

        public override bool SupressMessages { get; set; } = false;

        public Flowsheet2(Action<string, IFlowsheet.MessageType> messageListener, Action updateUIhandler)
        {

            GetSpreadsheetObjectFunc = () => Spreadsheet;

            LoadSpreadsheetData = new Action<XDocument>((xdoc) =>
            {
                if (xdoc.Element("DWSIM_Simulation_Data").Element("Spreadsheet") != null)
                {
                    var rgfdataelement = xdoc.Element("DWSIM_Simulation_Data").Element("Spreadsheet").Element("RGFData");
                    if (rgfdataelement != null)
                    {
                        string rgfdata = xdoc.Element("DWSIM_Simulation_Data").Element("Spreadsheet").Element("RGFData").Value;
                        rgfdata = rgfdata.Replace("Calibri", "Arial").Replace("10.25", "10");
                        Dictionary<string, string> sdict = new Dictionary<string, string>();
                        sdict = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(rgfdata);
                        Spreadsheet.RemoveWorksheet(0);
                        foreach (var item in sdict)
                        {
                            var tmpfile = SharedClasses.Utility.GetTempFileName();
                            var sheet = Spreadsheet.CreateWorksheet(item.Key);
                            Spreadsheet.Worksheets.Add(sheet);
                            var xmldoc = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(item.Value);
                            xmldoc.Save(tmpfile);
                            sheet.LoadRGF(tmpfile);
                            File.Delete(tmpfile);
                        }
                    }
                }
            });

            SaveSpreadsheetData = new Action<XDocument>((xdoc) =>
            {
                xdoc.Element("DWSIM_Simulation_Data").Add(new XElement("Spreadsheet"));
                xdoc.Element("DWSIM_Simulation_Data").Element("Spreadsheet").Add(new XElement("RGFData"));
                var tmpfile = SharedClasses.Utility.GetTempFileName();
                Dictionary<string, string> sdict = new Dictionary<string, string>();
                foreach (var sheet in Spreadsheet.Worksheets)
                {
                    var tmpfile2 = SharedClasses.Utility.GetTempFileName();
                    sheet.SaveRGF(tmpfile2);
                    var xmldoc = new XmlDocument();
                    xmldoc.Load(tmpfile2);
                    sdict.Add(sheet.Name, Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmldoc));
                    File.Delete(tmpfile2);
                }
                xdoc.Element("DWSIM_Simulation_Data").Element("Spreadsheet").Element("RGFData").Value = Newtonsoft.Json.JsonConvert.SerializeObject(sdict);
            });

            RetrieveSpreadsheetData = new Func<string, List<string[]>>((range) =>
            {
                return GetSpreadsheetDataFromRange(range);
            });

            RetrieveSpreadsheetFormat = new Func<string, List<string[]>>((range) =>
            {
                return GetSpreadsheetFormatFromRange(range);
            });

            DynamicsManager.RunSchedule = (schname) =>
            {
                DynamicsManager.CurrentSchedule = DynamicsManager.GetSchedule(schname).ID;
                return null;
            };

            listeningaction = messageListener;

            updateUIaction = updateUIhandler;

        }

        private List<string[]> GetSpreadsheetDataFromRange(string range)
        {

            var list = new List<string[]>();
            var slist = new List<string>();

            var rdata = Spreadsheet.Worksheets[0].GetRangeData(new RangePosition(range));

            for (var i = 0; i < rdata.GetLength(0); i++)
            {
                slist = new List<string>();
                for (var j = 0; j < rdata.GetLength(1); j++)
                {
                    slist.Add(rdata[i, j] != null ? rdata[i, j].ToString() : "");
                }
                list.Add(slist.ToArray());
            }

            return list;
        }

        private List<string[]> GetSpreadsheetFormatFromRange(string range)
        {

            var list = new List<string[]>();
            var slist = new List<string>();

            var rdata = Spreadsheet.Worksheets[0].GetRangeData(new RangePosition(range));

            for (var i = 0; i < rdata.GetLength(0); i++)
            {
                slist = new List<string>();
                for (var j = 0; j < rdata.GetLength(1); j++)
                {
                    var format = Spreadsheet.Worksheets[0].Cells[i, j].DataFormat;
                    if (format == CellDataFormatFlag.Number)
                    {
                        var args = (NumberDataFormatter.NumberFormatArgs)(Spreadsheet.Worksheets[0].Cells[i, j].DataFormatArgs);
                        slist.Add("N" + args.DecimalPlaces);
                    }
                    else
                    {
                        slist.Add("");
                    }
                }
                list.Add(slist.ToArray());
            }

            return list;
        }

        private void SetCustomSpreadsheetFunctions()
        {

            FormulaExtension.CustomFunctions["GETNAME"] = (cell, args) =>
            {
                try
                {
                    return SimulationObjects[args[0].ToString()].GraphicObject.Tag;
                }
                catch (Exception ex)
                {
                    return "ERROR: " + ex.Message;
                }
            };

            FormulaExtension.CustomFunctions["GETPROPVAL"] = (cell, args) =>
            {
                if (args.Length == 2)
                {
                    try
                    {
                        return SimulationObjects[args[0].ToString()].GetPropertyValue(args[1].ToString());
                    }
                    catch (Exception ex)
                    {
                        return "ERROR: " + ex.Message;
                    }
                }
                else if (args.Length == 3)
                {
                    try
                    {
                        var obj = SimulationObjects[args[0].ToString()];
                        var val = obj.GetPropertyValue(args[1].ToString());
                        return General.ConvertUnits(double.Parse(val.ToString()), obj.GetPropertyUnit(args[1].ToString()), args[2].ToString());
                    }
                    catch (Exception ex)
                    {
                        return "ERROR: " + ex.Message;
                    }
                }
                else
                    return "INVALID ARGS";
            };

            FormulaExtension.CustomFunctions["SETPROPVAL"] = (cell, args) =>
            {
                if (args.Length == 3)
                {
                    try
                    {
                        var ws = cell.Worksheet;
                        var wcell = ws.Cells[ws.RowCount - 1, ws.ColumnCount - 1];
                        wcell.Data = null;
                        wcell.Formula = args[2].ToString().Trim('"');
                        Evaluator.Evaluate(wcell);
                        var val = wcell.Data;
                        if (wcell.Data == null)
                        {
                            val = wcell.Formula;
                        }
                        SimulationObjects[args[0].ToString()].SetPropertyValue(args[1].ToString(), val);
                        wcell.Formula = null;
                        wcell.Data = null;
                        return string.Format("EXPORT OK [{0}, {1} = {2}]", SimulationObjects[args[0].ToString()].GraphicObject.Tag, args[1].ToString(), val);
                    }
                    catch (Exception ex)
                    {
                        return "ERROR: " + ex.Message;
                    }
                }
                else if (args.Length == 4)
                {
                    try
                    {
                        var obj = SimulationObjects[args[0].ToString()];
                        var prop = args[1].ToString();
                        var ws = cell.Worksheet;
                        var wcell = ws.Cells[ws.RowCount - 1, ws.ColumnCount - 1];
                        wcell.Formula = args[2].ToString().Trim('"');
                        Evaluator.Evaluate(wcell);
                        var val = wcell.Data;
                        wcell.Formula = "";
                        wcell.Data = "";
                        var units = args[3].ToString();
                        var newval = General.ConvertUnits(double.Parse(val.ToString()), units, obj.GetPropertyUnit(prop));
                        obj.SetPropertyValue(prop, newval);
                        return string.Format("EXPORT OK [{0}, {1} = {2} {3}]", obj.GraphicObject.Tag, prop, val, units);
                    }
                    catch (Exception ex)
                    {
                        return "ERROR: " + ex.Message;
                    }
                }
                else
                    return "INVALID ARGS";
            };

            FormulaExtension.CustomFunctions["GETPROPUNITS"] = (cell, args) =>
            {
                if (args.Length == 2)
                {
                    try
                    {
                        return SimulationObjects[args[0].ToString()].GetPropertyUnit(args[1].ToString());
                    }
                    catch (Exception ex)
                    {
                        return "ERROR: " + ex.Message;
                    }
                }
                else
                    return "INVALID ARGS";
            };

            FormulaExtension.CustomFunctions["GETOBJID"] = (cell, args) =>
            {
                if (args.Length == 1)
                {
                    try
                    {
                        return GetFlowsheetSimulationObject(args[0].ToString()).Name;
                    }
                    catch (Exception ex)
                    {
                        return "ERROR: " + ex.Message;
                    }
                }
                else
                    return "INVALID ARGS";
            };

            FormulaExtension.CustomFunctions["GETOBJNAME"] = (cell, args) =>
            {
                if (args.Length == 1)
                {
                    try
                    {
                        return SimulationObjects[args[0].ToString()].GraphicObject.Tag;
                    }
                    catch (Exception ex)
                    {
                        return "ERROR: " + ex.Message;
                    }
                }
                else
                    return "INVALID ARGS";
            };
        }

        public void Init()
        {

            Initialize();

            Spreadsheet = unvell.ReoGrid.ReoGridControl.CreateMemoryWorkbook();

            SetCustomSpreadsheetFunctions();

        }

        public override IFlowsheet GetNewInstance()
        {
            var fs = new Flowsheet2(null, null);
            return fs;
        }

        public override void UpdateInformation()
        {
            UpdateInterface();
        }

        public override void UpdateInterface()
        {
            updateUIaction?.Invoke();
        }

        public override void ShowDebugInfo(string text, int level)
        {
            Console.WriteLine(text);
        }

        public override void ShowMessage(string text, IFlowsheet.MessageType mtype, string exceptionid = "")
        {
            if (listeningaction != null) listeningaction(text, mtype);
        }

        public void WriteMessage(string text)
        {
            listeningaction?.Invoke(text, IFlowsheet.MessageType.Information);
        }

        public override void UpdateOpenEditForms()
        {

        }

        public override object GetApplicationObject()
        {
            return null;
        }

        public void SolveFlowsheet()
        {

            if (PropertyPackages.Count == 0)
            {
                throw new Exception("Please select a Property Package before solving the flowsheet.");
            }

            if (SelectedCompounds.Count == 0)
            {
                throw new Exception("Please select a Compound before solving the flowsheet.");
            }

            Settings.CalculatorActivated = true;
            Settings.SolverMode = 1;
            Settings.SolverBreakOnException = true;

            RequestCalculation();

        }

        public List<Exception> SolveFlowsheet2()
        {
            if (PropertyPackages.Count == 0)
            {
                ShowMessage("Please select a Property Package before solving the flowsheet.", IFlowsheet.MessageType.GeneralError);
                return new List<Exception>();
            }

            if (SelectedCompounds.Count == 0)
            {
                ShowMessage("Please select a Compound before solving the flowsheet.", IFlowsheet.MessageType.GeneralError);
                return new List<Exception>();
            }

            Settings.CalculatorActivated = true;

            Task<List<Exception>> st = new Task<List<Exception>>(() =>
            {
                return FlowsheetSolver.FlowsheetSolver.SolveFlowsheet(this, GlobalSettings.Settings.SolverMode);
            });

            st.ContinueWith((t) =>
            {
                Settings.CalculatorStopRequested = false;
                Settings.CalculatorBusy = false;
                Settings.TaskCancellationTokenSource = new System.Threading.CancellationTokenSource();
            });

            try
            {
                st.Start(TaskScheduler.Default);
                st.Wait();
                return st.Result;
            }
            catch (AggregateException aex)
            {
                foreach (Exception ex2 in aex.InnerExceptions)
                {
                    ShowMessage(ex2.ToString(), IFlowsheet.MessageType.GeneralError);
                }
                Settings.CalculatorBusy = false;
                Settings.TaskCancellationTokenSource = new System.Threading.CancellationTokenSource();
                return new List<Exception>(aex.InnerExceptions);
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString(), IFlowsheet.MessageType.GeneralError);
                Settings.CalculatorBusy = false;
                Settings.TaskCancellationTokenSource = new System.Threading.CancellationTokenSource();
                return new List<Exception> { ex };
            }

        }

        public override void SetMessageListener(Action<string, IFlowsheet.MessageType> act)
        {
            listeningaction = act;
        }

        public void GenerateReport(List<ISimulationObject> objects, string format, Stream ms)
        {

            string ptext = "";

            switch (format)
            {

                case "PDF":

                    iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30);
                    var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms);

                    var bf = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER, iTextSharp.text.pdf.BaseFont.CP1252, true);

                    var regfont = new Font(bf, 12, Font.NORMAL);
                    var boldfont = new Font(bf, 12, Font.BOLD);

                    document.Open();
                    document.Add(new Paragraph("DWSIM Simulation Results Report", boldfont));
                    document.Add(new Paragraph("Simulation Name: " + Options.SimulationName, boldfont));
                    document.Add(new Paragraph("Date created: " + System.DateTime.Now.ToString() + "\n\n", boldfont));

                    foreach (var obj in objects)
                    {
                        ptext = obj.GetDisplayName() + ": " + obj.GraphicObject.Tag + "\n\n";
                        document.Add(new Paragraph(ptext, boldfont));
                        ptext = obj.GetReport(Options.SelectedUnitSystem, System.Globalization.CultureInfo.CurrentCulture, Options.NumberFormat);
                        ptext += "\n";
                        document.Add(new Paragraph(ptext, regfont));
                    }

                    document.Close();

                    writer.Close();

                    break;

                case "TXT":

                    string report = "";

                    report += "DWSIM Simulation Results Report\nSimulation Name: " + Options.SimulationName + "\nDate created: " + System.DateTime.Now.ToString() + "\n\n";

                    foreach (var obj in objects)
                    {
                        ptext = "";
                        ptext += obj.GetDisplayName() + ": " + obj.GraphicObject.Tag + "\n\n";
                        ptext += obj.GetReport(Options.SelectedUnitSystem, System.Globalization.CultureInfo.CurrentCulture, Options.NumberFormat);
                        ptext += "\n";
                        report += ptext;
                    }


                    using (StreamWriter wr = new StreamWriter(ms))
                    {
                        wr.Write(report);
                    }
                    break;

                default:

                    throw new NotImplementedException("Sorry, this feature is not yet available.");
            }

        }

        public override void RunCodeOnUIThread(Action act)
        {
            act.Invoke();
        }

        public override void DisplayForm(object form)
        {
            throw new NotImplementedException();
        }
        public void SaveSimulation(string path, bool backup = false)
        {

            if (System.IO.Path.GetExtension(path).ToLower() == ".dwxmz")
            {

                path = Path.ChangeExtension(path, ".dwxmz");

                string xmlfile = Path.ChangeExtension(GetTempFileName(), ".xml");

                SaveToXML().Save(xmlfile);

                var i_Files = new List<string>();
                if (File.Exists(xmlfile))
                    i_Files.Add(xmlfile);

                var strmZipOutputStream = new ZipOutputStream(File.Create(path));

                strmZipOutputStream.SetLevel(9);

                if (Options.UsePassword)
                    strmZipOutputStream.Password = Options.Password;

                string strFile = "";

                foreach (string strFile_loopVariable in i_Files)
                {
                    strFile = strFile_loopVariable;
                    FileStream strmFile = File.OpenRead(strFile);
                    byte[] abyBuffer = new byte[strmFile.Length];

                    strmFile.Read(abyBuffer, 0, abyBuffer.Length);
                    ZipEntry objZipEntry = new ZipEntry(Path.GetFileName(strFile));

                    objZipEntry.DateTime = DateTime.Now;
                    objZipEntry.Size = strmFile.Length;
                    strmFile.Close();
                    strmZipOutputStream.PutNextEntry(objZipEntry);
                    strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length);

                }

                strmZipOutputStream.Finish();
                strmZipOutputStream.Close();

                try
                {
                    File.Delete(xmlfile);
                }
                catch { }
                //try
                //{
                //    File.Delete(dbfile);
                //}
                //catch { }
            }
            else if (System.IO.Path.GetExtension(path).ToLower() == ".dwxml")
            {
                SaveToXML().Save(path);
            }
            else if (System.IO.Path.GetExtension(path).ToLower() == ".xml")
            {
                SaveToMXML().Save(path);
            }

            ProcessScripts(EventType.SimulationSaved, ObjectType.Simulation, "");

        }

        private string GetTempFileName()
        {
            return Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.tmp");
        }

        public override void CloseOpenEditForms()
        {

        }

        public override IFlowsheet Clone()
        {

            var fs = new Flowsheet2(null, null);
            fs.Initialize();
            var xdoc = SaveToXML();
            fs.LoadFromXML(xdoc);
            return fs;

        }

    }
}