aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/MainWindowVM.cs
blob: 33b0cb2f7425a393dd038d9066b7357c68b5ef63 (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
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
<UserControl x:Class="Tango.FSE.PPCConsole.Dialogs.MachineUpdateView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:material="http://materialdesigninxaml.net/winfx/xaml/themes"
             xmlns:controls="clr-namespace:Tango.SharedUI.Controls;assembly=Tango.SharedUI"
             xmlns:local="clr-namespace:Tango.FSE.PPCConsole.Dialogs"
             mc:Ignorable="d" 
             Width="1000" Height="600" d:DataContext="{d:DesignInstance Type=local:MachineUpdateViewVM, IsDesignTimeCreatable=False}" Background="{StaticResource FSE_PrimaryBackgroundLightBrush}" Foreground="{StaticResource FSE_PrimaryForegroundBrush}">
    <DockPanel Margin="10">

        <StackPanel Orientation="Horizontal" DataContext="{Binding Update}" DockPanel.Dock="Top">
            <material:PackIcon Width="42" Height="42" VerticalAlignment="Center">
                <material:PackIcon.Style>
                    <Style TargetType="material:PackIcon">
                        <Setter Property="Kind" Value="Information"></Setter>
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding IsSetup}" Value="True">
                                <Setter Property="Kind" Value="Settings"></Setter>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IsUpdate}" Value="True">
                                <Setter Property="Kind" Value="CloudDownload"></Setter>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IsDataBase}" Value="True">
                                <Setter Property="Kind" Value="Database"></Setter>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IsSynchronization}" Value="True">
                                <Setter Property="Kind" Value="Sync"></Setter>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IsOfflineUpdate}" Value="True">
                                <Setter Property="Kind" Value="Sd"></Setter>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IsOfflineFirmwareUpgrade}" Value="True">
                                <Setter Property="Kind" Value="Chip"></Setter>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IsStarted}" Value="True">
                                <Setter Property="Foreground" Value="{StaticResource FSE_WarningBrush}"></Setter>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IsCompleted}" Value="True">
                                <Setter Property="Foreground" Value="{StaticResource FSE_SuccessBrush}"></Setter>
                            </DataTrigger>
                            <DataTrigger Binding="{Binding IsFailed}" Value="True">
                                <Setter Property="Foreground" Value="{StaticResource FSE_ErrorBrush}"></Setter>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </material:PackIcon.Style>
            </material:PackIcon>
            <TextBlock VerticalAlignment="Center" Text="{Binding UpdateStatus,Converter={StaticResource EnumToDescriptionConverter}}" TextWrapping="NoWrap" Height="22" TextTrimming="CharacterEllipsis" Width="700" Margin="10 0 0 0" FontSize="{StaticResource FSE_LargeFontSize}"></TextBlock>
        </StackPanel>

        <Grid Margin="0 10 0 0" DockPanel.Dock="Top">
            <controls:TableGrid RowHeight="30">
                <TextBlock Text="Started On:" FontWeight="SemiBold" />
                <TextBlock Text="{Binding Update.StartDate,Converter={StaticResource DateTimeUTCToShortDateTimeConverter}}"></TextBlock>
                <TextBlock Text="Application:" FontWeight="SemiBold" />
                <TextBlock Text="{Binding Update.ApplicationVersion}"></TextBlock>
                <TextBlock Text="Firmware:" FontWeight="SemiBold" />
                <TextBlock Text="{Binding Update.FirmwareVersion}"></TextBlock>
                <TextBlock Text="Ended:" FontWeight="SemiBold" />
                <TextBlock Text="{Binding Update.EndDate,TargetNullValue='Never',FallbackValue='Never',Converter={StaticResource DateTimeUTCToShortDateTimeConverter}}"></TextBlock>
            </controls:TableGrid>
        </Grid>

        <Border Padding="5" BorderThickness="1" BorderBrush="{StaticResource FSE_BorderBrush}">
            <TextBox BorderThickness="0" Foreground="{StaticResource FSE_PrimaryForegroundBrush}" Text="{Binding Update.FailedLog,TargetNullValue='No further Information available.'}" Style="{x:Null}" TextWrapping="NoWrap" IsReadOnly="True" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Background="Transparent" />
        </Border>
    </DockPanel>
</UserControl>
'>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 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using Microsoft.WindowsAPICodePack.Dialogs;
using Tango.Core.Commands;
using Tango.CSV;
using Tango.DispenserAnalyzer.UI.Models;
using Tango.SharedUI;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Tango.DispenserAnalyzer.UI.Analysis;
using System.Windows;
using System.Windows.Threading;
using OxyPlot;
using OxyPlot.Wpf;
using OxyPlot.Annotations;
using System.Windows.Media;
using System.Diagnostics;
using System.Windows.Documents;
using System.Windows.Controls;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using System.Windows.Media.Imaging;
using PdfSharp;
using OxyPlot.Reporting;
using Tango.Documents;
using Tango.DispenserAnalyzer.UI.View;
using Tango.Core.Helpers;
using Tango.DispenserAnalyzer.UI.ExcelModel;
using Tango.DispenserAnalyzer.UI.Analyzers;
using static Tango.DispenserAnalyzer.UI.Analyzers.FlowAnalyser;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Globalization;

namespace Tango.DispenserAnalyzer.UI.ViewModels
{
    public class MainWindowVM: ViewModel
    {
        private const string FILE_EXTENSION = ".pdf";
        private string _settingsFilepath = "";
        
        #region Properties

        public Plot PlotControl { get; set; }

        /// <summary>
        /// Gets or sets the results panel. Using to save all results in xps file
        /// </summary>
        public System.Windows.Controls.ItemsControl ResultsPanel { get; set; }

        private string _openFilePath;
        public string OpenFilePath
        {
            get { return _openFilePath; }
            set
            {
                if(value != null && _openFilePath != value)
                {
                    _openFilePath = value;
                    OnSelectedFileChanged();
                    RaisePropertyChangedAuto();
                    GenerateCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private string _filename;
        public string FileName
        {
            get { return _filename; }
            set {   _filename = value;
                    RaisePropertyChangedAuto();
                    RaisePropertyChanged("ButtonName"); }
        }

        public string ButtonName {
            get { return "Generate result for " + FileName; }
             }

        private string _testName = "";
        public string TestName
        {
            get { return _testName.ToUpper() + " TEST"; }
            set { _testName = value; RaisePropertyChangedAuto(); }
        }
        
        private IList<DataPoint> _points;
        /// <summary>
        /// Binding to ItemsSource  of line chart.
        /// </summary>
        public IList<DataPoint> Points
        {
            get { return _points; }
            set
            {
                _points = value;
                RaisePropertyChangedAuto();
            }
        }
        private int _step;
        public int XStep
        {
            get { return _step; }
            set { _step = value; RaisePropertyChangedAuto(); }
        }
        
        private double _from;
        /// <summary>
        /// From use to binding to bottom axis min value
        /// </summary>
        public double From
        {
            get { return _from; }
            set
            {
                _from = value; RaisePropertyChangedAuto();
            }
        }
        
        private double _to;
        /// <summary>
        /// To use to binding to bottom axis max value
        /// </summary>
        public double To
        {
            get { return _to; }
            set
            {
                _to = value; RaisePropertyChangedAuto();
            }
        }

        private string _titleAxisBottom;

        public string TitleAxisBottom
        {
            get { return _titleAxisBottom; }
            set { _titleAxisBottom = value; RaisePropertyChangedAuto(); }
        }

        private string _titleAxisLeft;

        public string TitleAxisLeft
        {
            get { return _titleAxisLeft; }
            set { _titleAxisLeft = value; RaisePropertyChangedAuto(); }
        }
        
        private bool _isRunning;
        /// <summary>
        /// Gets or sets a value indicating whether this instance is running.
        /// </summary>
        public bool IsRunning
        {
            get { return _isRunning; }
            set { _isRunning = value; RaisePropertyChangedAuto(); }
        }
        
        private ObservableCollection<IAnalyzerResult> _analyzerResults;
        public ObservableCollection<IAnalyzerResult> AnalyzerResults
        {
            get { return _analyzerResults; }
            set { _analyzerResults = value; RaisePropertyChangedAuto(); }
        }
        
        public Func<double, string> YFormatter { get; set; }

        private Visibility _isCompareVisible;

        public Visibility IsCompareVisible
        {
            get { return _isCompareVisible; }
            set { _isCompareVisible = value;
                RaisePropertyChangedAuto();
            }
        }

        private bool _addToComare;

        public bool AddToComare
        {
            get { return _addToComare; }
            set { _addToComare = value;
                OnAddToCompareResults(value);
                RaisePropertyChangedAuto();
            }
        }

        private string _compareResText1;

        public string CompareResText1
        {
            get {
                if (String.IsNullOrEmpty(_compareResText1))
                    return "Empty";
                   return _compareResText1;
            }
            set {
                _compareResText1 = value;
                RaisePropertyChangedAuto();
            }
        }

        private string _compareResText2;

        public string CompareResText2
        {
            get {
                if (String.IsNullOrEmpty(_compareResText2))
                    return "Empty";
                return _compareResText2; }
            set { _compareResText2 = value;
                RaisePropertyChangedAuto();
            }
        }

        private bool _isAddedRes1;

        public bool IsAddedRes1
        {
            get { return _isAddedRes1; }
            set { _isAddedRes1 = value;
                RaisePropertyChangedAuto();
            }
        }

        private bool _isAddedRes2;

        public bool IsAddedRes2
        {
            get { return _isAddedRes2; }
            set { _isAddedRes2 = value;
                RaisePropertyChangedAuto();
            }
        }

        private ObservableCollection<CompareResultModel> _resultsToCompare;

        public ObservableCollection<CompareResultModel> ResultsToCompare
        {
            get { return _resultsToCompare; }
            set { _resultsToCompare = value; }
        }


        #endregion

        #region Commands

        public RelayCommand OpenCSVFileCommand { get; set; }
        public RelayCommand GenerateCommand { get; set; }
        public RelayCommand OpenSettingWndCommand { get; set; }
        public RelayCommand CompareCommand { get; set; }
        public RelayCommand SaveExelCommand { get; set; }
        #endregion

        public MainWindowVM()
        {
            ResultsToCompare = new ObservableCollection<CompareResultModel>();
           
            OpenCSVFileCommand = new RelayCommand(OpenCSVFile);
            GenerateCommand = new RelayCommand(Generate, CanGenerate);
            OpenSettingWndCommand = new RelayCommand(OpenSettingWnd);
            CompareCommand = new RelayCommand(Compareresults, CanCompareresults);
            SaveExelCommand = new RelayCommand(SaveExel, CanSaveExel);

            YFormatter = value => value.ToString();
            _from = 0;
            _to = 1;
            XStep = 1;
            AnalyzerResults = new ObservableCollection<IAnalyzerResult>();
            _isRunning = false;
            TitleAxisBottom = "";
            TitleAxisLeft = "";
            this.Points = new List<DataPoint>();
            IsCompareVisible = Visibility.Collapsed;
            IsAddedRes1 = IsAddedRes2 = false;
            InitUserSettings();
        }

        #region Settings

        public void InitUserSettings()
        {
            string folderPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DispenserAnalyzer");
            Directory.CreateDirectory(folderPath);
            _settingsFilepath = System.IO.Path.Combine(folderPath, "Settings.json");

            try
            {
                Settings.DeserializeSettings(_settingsFilepath);
            }
            catch (IOException ex)
            {
                MessageBox.Show("Warning: " + ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        
        public void OpenSettingWnd()
        {
            SettingsWnd settings = new SettingsWnd();
            settings.Owner = System.Windows.Application.Current.MainWindow;
            if(true == settings.ShowDialog())
            {
                Dictionary<AnalyzerSettingsEnum, object>  changes = settings.GetChanges();
                foreach (KeyValuePair<AnalyzerSettingsEnum, object> entry in changes)
                {
                    Settings.SetValueByName(entry.Key, entry.Value);
                }
                try
                {
                    Settings.SerializeSettings(_settingsFilepath);
                }
                catch (IOException ex)
                {
                    MessageBox.Show("Warning: " + ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }

        private void ClearResults()
        {
            IsCompareVisible = Visibility.Collapsed;
            _addToComare = false;
            RaisePropertyChanged("AddToComare");
            Points.Clear();

            AnalyzerResults.Clear();
            TestName = "";
            foreach (var ax in PlotControl.Axes)
            {
                ax.Maximum = ax.Minimum = Double.NaN;
                PlotControl.ResetAllAxes();
            }
            PlotControl.Annotations.Clear();
            PlotControl.InvalidatePlot(true);
        }

        #endregion

        #region Read File
        private void OpenCSVFile()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "CSV Files|*.csv";
            if (dlg.ShowDialog().Value)
            {
                try
                {
                    OpenFilePath = dlg.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occurred while trying to import the CSV file. " + ex.Message,
                                          "Warning",
                                          MessageBoxButton.OK,
                                          MessageBoxImage.Warning);
                }
            }
        }
        protected virtual bool IsFileLocked(string filePath)
        {
            FileStream stream = null;
            try
            {
                stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
            }
            catch (IOException ex)
            {
                MessageBox.Show("Warning: " + ex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                return true;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
            return false;
        }

        private void OnSelectedFileChanged()
        {
            ClearResults();
            if(File.Exists(OpenFilePath))
            {
                FileHelper.OpenFilePath = OpenFilePath;
                FileName = Path.GetFileName(OpenFilePath);
            }
            SaveExelCommand.RaiseCanExecuteChanged();
        }
        #endregion
        
        #region Generate

        public bool CanGenerate()
        {
            var value = (OpenFilePath != null && OpenFilePath.Length != 0 && File.Exists(OpenFilePath));
            return (OpenFilePath!= null && OpenFilePath.Length != 0 && File.Exists(OpenFilePath));
        }

        /// <summary>
        /// Generates all results.
        /// </summary>
        public async void Generate()
        {
            if (false == File.Exists(OpenFilePath) || IsFileLocked(OpenFilePath))
                return;
            ClearResults();

            var analyzer = AnalysisService.GetAnalyzer(OpenFilePath);
            if (analyzer == null)
                return;

            IsRunning = true;
            AnalyzerAttribute[] attr = analyzer.GetType().GetCustomAttributes(typeof(AnalyzerAttribute), true);
            if (attr != null && attr.Count() > 0)
            {
                TestName = attr[0].Name;
            }
            List<OxyPlot.Wpf.LineAnnotation> annotations = new List<OxyPlot.Wpf.LineAnnotation>();
            var samples = analyzer.Reader.ReadScvFile(OpenFilePath, annotations);
            bool showChartAfterProcess = analyzer.ShowChartAfterProcess;
            if (false == showChartAfterProcess)
            {
                analyzer.GetPoints(samples, Points);
                if (Points.Count == 0)
                {
                    IsRunning = false;
                    return;
                }
            }

            //visible only for process type
            IsCompareVisible = analyzer.AvailableCompareResults ? Visibility.Visible : Visibility.Collapsed;

            annotations.ForEach(x => PlotControl.Annotations.Add(x));
            To = 0;
            From = 0;
          
            List<IAnalyzerResult> res = await analyzer.Process(samples, false);
            AnalyzerResults = new ObservableCollection<IAnalyzerResult>(res);
            if (showChartAfterProcess)
            {
                analyzer.GetPoints(samples, Points);
                if (Points.Count == 0)
                {
                    IsRunning = false;
                    return;
                }
            }

            _to = Points.Max(x => x.Y);
            _from = TestName.Contains("sealtest") ? Points.FirstOrDefault(x => x.X == 0).Y : Points.Min(x => x.Y);
            List<string> titles = analyzer.Reader.GetTitles(OpenFilePath);
            TitleAxisBottom = titles[0];
            TitleAxisLeft = titles[1];

            // data.Clear();
            _to += 100;
            RaisePropertyChanged("To");
            if (_from != 0)
                _from -= 100;
            RaisePropertyChanged("From");
            XStep = (int)(Points.Count / 5);

            IsRunning = false;
            PlotControl.InvalidatePlot(true);
            
            if(analyzer.Reader.PrintResultsToPDFFile())
            {
                await PrintToXpsFile();
            }
            InvalidateRelayCommands();
        }

        /// <summary>
        /// Generates all results from command line and close application.
        /// </summary>
        public async Task GenerateInBackground(string openFilePath)
        {
            OpenFilePath = openFilePath;

            if (false == File.Exists(OpenFilePath) || IsFileLocked(OpenFilePath))
                return;

            var analyzer = AnalysisService.GetAnalyzer(OpenFilePath);
            if (analyzer == null)
                return;

            AnalyzerAttribute[] attr = analyzer.GetType().GetCustomAttributes(typeof(AnalyzerAttribute), true);
            if (attr != null && attr.Count() > 0)
            {
                TestName = attr[0].Name;
            }

            List<OxyPlot.Wpf.LineAnnotation> annotations = new List<OxyPlot.Wpf.LineAnnotation>();
            var samples = analyzer.Reader.ReadScvFile(OpenFilePath, annotations);
            analyzer.GetPoints(samples, Points);
            if (Points.Count == 0)
            {
                return;
            }
           
            List<IAnalyzerResult> res = await analyzer.Process(samples, true);
            AnalyzerResults = new ObservableCollection<IAnalyzerResult>(res);
            

            await ExportResultsToTextFile();
        }

        #endregion
        
        #region SaveInXps file
        private async Task PrintToXpsFile()
        {
            await Task.Delay(200);
            try
            {
                var resultFile = FileHelper.GetResultFilePath();
                if (resultFile.IsNotNullOrEmpty())
                {
                    SaveResultsAsXps(resultFile);
                }
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
       
        public void SaveResultsAsXps( string fileName)
        {
            var dir = Path.GetDirectoryName(fileName);
            var name = Path.GetFileNameWithoutExtension(fileName);
            string fileNameWithoutExtension = Path.Combine(dir, name);

            ContentControl cc = ResultsPanel.Parent as ContentControl;
            ResultsPanel.UpdateLayout();

            List<Plot> all_plots = ResultsPanel.FindVisualChildren<OxyPlot.Wpf.Plot>().ToList();
            List<Plot> plots = new List<Plot>();
            List<System.Windows.Controls.Image> plotimages = new List<System.Windows.Controls.Image>();
            int index = 0;
            foreach (var item in all_plots)
            {
                var seriesdata = item.Series[0].ItemsSource;

                item.RaiseEvent(new System.Windows.RoutedEventArgs(OxyPlot.Wpf.PlotView.LoadedEvent));
                item.InvalidatePlot(true);
                if (item.IsMeasureValid && item.ActualHeight > 0)
                {
                    plots.Add(item);
                    string pngPlotFileName = String.Format($"{fileNameWithoutExtension}_Plottest{index}.png");
                    File.Delete(pngPlotFileName);
                    System.Windows.Controls.Image plotImage = new System.Windows.Controls.Image();
                    //print plot to png file - removed 2/07/2020
                   //using (var stream = File.Open(pngPlotFileName, FileMode.Create, FileAccess.ReadWrite))
                    {
                        PngExporter exporter = new PngExporter() { Width = (int)item.ActualWidth, Height = (int)item.ActualHeight, Background = OxyColors.White, Resolution = 96 };
                        //exporter.Export(item.ActualModel, stream);

                        BitmapSource bitmap = exporter.ExportToBitmap(item.ActualModel);
                        plotImage.Source = bitmap;
                        plotImage.UpdateLayout();
                        var parent = item.Parent;
                        if (parent is Panel)
                        {
                            var plpanel = (Panel)parent;
                            plpanel.Children.Remove(item);
                            plpanel.Children.Add(plotImage);
                            plpanel.UpdateLayout();
                        }
                        else if (parent is Decorator)
                        {
                            ((Decorator)parent).Child = plotImage;
                            ((Border)parent).UpdateLayout();
                        }
                    }
                    plotimages.Add(plotImage);
                    index++;
                }
                ResultsPanel.UpdateLayout();
            }
            
            if (cc != null)
            {
                cc.Content = null;
                CreateDoc(fileName, plots, plotimages);
                cc.Content = ResultsPanel;
            }
        }

        private void CreateDoc( string fileName, List<Plot> plots, List<System.Windows.Controls.Image> plotimages)
        {
            Dispatcher.CurrentDispatcher.Invoke( DispatcherPriority.Loaded, new Action(() =>
                         {
                             var dir = Path.GetDirectoryName(fileName);
                             var name = Path.GetFileNameWithoutExtension(fileName);
                             string fileNameWithoutExtension = Path.Combine(dir, name);

                             Size reportSize = GetReportSize(ResultsPanel);

                             FixedDocument fixedDoc = new FixedDocument();
                             PageContent pageContent = new PageContent();
                             FixedPage fixedPage = new FixedPage();
                             fixedPage.Width = reportSize.Width;
                             fixedPage.Height = reportSize.Height;
                             fixedPage.Children.Add(ResultsPanel);
                             fixedPage.UpdateLayout();

                             pageContent.BeginInit();
                             ((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
                             pageContent.EndInit();

                             fixedDoc.Pages.Add(pageContent);

                             InjectData(fixedDoc, AnalyzerResults);
                             ResultsPanel.Measure(reportSize);
                             ResultsPanel.Arrange(new Rect(new Point(0, 0), ResultsPanel.DesiredSize));
                             ResultsPanel.UpdateLayout();


                             String sourceXpsFile = String.Format($"{fileNameWithoutExtension}_test.xps");
                             File.Delete(sourceXpsFile);
                             using (XpsDocument xpsd = new XpsDocument(sourceXpsFile, FileAccess.Write))
                             {
                                 System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
                                 xw.Write(fixedDoc);
                             }
                             fixedPage.Children.Remove(ResultsPanel);
                             PdfSharp.Xps.XpsConverter.Convert(sourceXpsFile, fileName, 0);
                             File.Delete(sourceXpsFile);
                         }));


        }

        /// <summary>
        /// Injects the data to printed document. Without this the binding data to elements doesn't work. 
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="dataSource">The data source.</param>
        protected void InjectData(FixedDocument document, object dataSource)
        {
            document.DataContext = new { AnalyzerResults = dataSource };
            // we need to give the binding infrastructure a push as we
            // are operating outside of the intended use of WPF
            var dispatcher = Dispatcher.CurrentDispatcher;
            dispatcher.Invoke(DispatcherPriority.SystemIdle,   new DispatcherOperationCallback(delegate { return null; }),   null);
        }

        private static Size GetReportSize(ItemsControl reportContainer)
        {
            double reportWidth = reportContainer.ActualWidth + 10;
            double reportHeight = reportContainer.ActualHeight + 10;// (reportWidth / printDialog.PrintableAreaWidth) * printDialog.PrintableAreaHeight;

            return new Size(reportWidth, reportHeight);
        }

        public static void Print(IPlotModel model, string fileName, double width, double height)
        {
            using (var stream = File.Open(fileName, FileMode.Create, FileAccess.ReadWrite))
            {
                var exporter = new XpsExporter { Width = width, Height = height};
                //PngExporter.Export(this.Plot.ActualModel, fileName, 600, 400, OxyColors.White)
                exporter.Export(model, stream);
            }
        }

        #endregion

        #region ExportToExel

        public async Task ExportResultsToTextFile()
        {
            var resultFile = FileHelper.GetResultFilePath();
            var dir = Path.GetDirectoryName(resultFile);
            var name = Path.GetFileNameWithoutExtension(resultFile);
            string fileNameWithoutExtension = Path.Combine(dir, name);
            String sourceFile = String.Format($"{fileNameWithoutExtension}s.txt");
            File.Delete(sourceFile);

            await Task.Factory.StartNew(() =>
            {
                try
                {
                    List<IAnalyzerResult> results = AnalyzerResults.ToList();
                   
                    using (StreamWriter outputFile = new StreamWriter(sourceFile))
                    {
                        outputFile.WriteLine(String.Format($"  {TestName.ToUpper()} RESULTS: "));
                        outputFile.WriteLine("");
                        outputFile.WriteLine("");
                        foreach (var res in results)
                        {
                            if (res.GetType().IsSubclassOf(typeof(AnalyzerResultBase)))
                            {
                                List<AnalyzerResultProperty> properties = (res as AnalyzerResultBase).Properties;
                                foreach (var prop in properties)
                                {
                                    outputFile.WriteLine(String.Format($"  {prop.Name} : {prop.Value}"));
                                }
                                string resV = String.Format($"   RESULT = {res.Result.ToString()}");
                                outputFile.WriteLine(resV);
                                outputFile.WriteLine("");
                            }
                        }
                        outputFile.Flush();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            });

        }

        public async void ExportFlowResultsToExcel()
        {
            string  filePath = (string)Settings.GetValueByName(AnalyzerSettingsEnum.DirectoryPath);

            if (!Directory.Exists(filePath))
            {
                CommonOpenFileDialog dialog = new CommonOpenFileDialog();
                dialog.InitialDirectory = "C:\\Users";
                dialog.IsFolderPicker = true;
                if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    filePath = dialog.FileName;
                    if (filePath.Count(x => x == '%') == 2)
                    {
                        var variable = Regex.Match(filePath, "(?<=%)(.*?)(?=%)").Value;
                        filePath = filePath.Replace($"%{variable}%", Environment.ExpandEnvironmentVariables($"%{variable}%"));
                    }
                    Settings.SetValueByName(AnalyzerSettingsEnum.DirectoryPath, filePath);
                    Settings.SetDefaultPath(filePath);
                }
                else
                {
                    MessageBox.Show("An error occurred while trying to open directory for saving result. ",
                                          "Warning",
                                          MessageBoxButton.OK,
                                          MessageBoxImage.Warning);
                    return;
                }
            }
            await Task.Run(() =>
            {
                ExcelWriter writer = null;
                ExcelReader reader = null;
                try
                {
                    IsFree = false;

                    Stream stream = null;
                    bool dispose = false;

                    if (false == filePath.EndsWith(@"\"))
                    {
                        filePath += @"\";
                    }
                    String file = filePath + $"DispensersData.xlsx";

                    if (File.Exists(file))
                    {
                        //stream = File.OpenRead(file);
                        stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        dispose = true;
                    }
                    else
                    {
                        var b = Assembly.GetExecutingAssembly().GetManifestResourceNames();
                        stream = EmbeddedResourceHelper.GetEmbeddedResourceStream("Tango.DispenserAnalyzer.UI.Templates.DispensersData.xlsx");
                    }
                    if (stream == null)
                        return;
                    
                    byte[] data = new byte[stream.Length];
                    stream.Read(data, 0, data.Length);
                    File.WriteAllBytes(file, data);

                    if (dispose)
                    {
                        stream.Dispose();
                    }
                    reader = new ExcelReader(file);
                    List<ExcelDataModel> old_threadCharacteristicsExelModels = reader.GetDataByIndex<ExcelDataModel>("Data", 2);
                    reader.Dispose();
                    reader = null;

                    
                    int maxNumber = old_threadCharacteristicsExelModels.Count > 0 ? old_threadCharacteristicsExelModels.OrderBy(x => x.No___of_test).Max(x => x.No___of_test) : 0;
                    maxNumber++;
                    var time_test = AnalysisService.GetDateTimeString(FileName);

                    var dispenser = AnalysisService.GetDispenserNumber(FileName);
                    int iterations = 0;
                    if (old_threadCharacteristicsExelModels.Count > 0)
                    {
                        var one_existed = old_threadCharacteristicsExelModels.OrderBy(x => x.No___of_test).Count(x => x.DISPENSER == dispenser && x.DATE == time_test);
                        if (one_existed > 0)
                        {
                            InvokeUI(() =>
                            {
                                var warningresult = MessageBox.Show($"The result is already saved for the dispenser {dispenser} at time {time_test}. Do you want to save it anyway?",
                                                  "Warning",
                                                  MessageBoxButton.YesNo,
                                                  MessageBoxImage.Question);
                                if(warningresult == MessageBoxResult.Cancel)
                                    return;
                            });
                        }
                        iterations = old_threadCharacteristicsExelModels.OrderBy(x => x.No___of_test).Count(x => x.DISPENSER == dispenser );
                        
                    }
                    iterations++;

                    //write results
                    List<ExcelDataModel> threadCharacteristicsExelModels = new List<ExcelDataModel>();
                    ExcelDataModel model = new ExcelDataModel();

                    model.No___of_test = maxNumber;//Could be defiend and saved
                    model.DISPENSER = dispenser;
                    model.iteration = iterations;
                    model.Location = FileName.IndexOf("CH8") > 0 ? "Dagesh" : "Twine";
                    model.DATE = time_test;
                    List<IAnalyzerResult> results = AnalyzerResults.ToList();
                    bool firstFlowAverageResult = true;
                    bool firstPrimingResult = true;
                    bool firstErrorResult = true;
                    bool pass = true;
                    foreach (var res in results)
                    {
                        if (res is PrimingAnalyzerResult)
                        {
                            if (firstPrimingResult)
                            {
                                model.PBU___sec__First_cycle = (res as PrimingAnalyzerResult).OnlyTime;
                                firstPrimingResult = false;
                            }
                            else
                            {
                                model.PBU___sec__Second_cycle = (res as PrimingAnalyzerResult).OnlyTime;
                            }
                        }
                        else if (res is FlowAverageAnalyzerResult)
                        {
                            if (firstFlowAverageResult)
                            {
                                model.Average_Value = (res as FlowAverageAnalyzerResult).AverageValue.ToString("0.##");
                                firstFlowAverageResult = false;
                                if ((res as FlowAverageAnalyzerResult).Result == AnalyzerResultValue.Failed)
                                    pass = false;
                            }
                            else
                            {
                                model.AverageValue2 = (res as FlowAverageAnalyzerResult).AverageValue.ToString("0.##");
                                if ((res as FlowAverageAnalyzerResult).Result == AnalyzerResultValue.Failed)
                                    pass = false;
                            }
                        }
                        else if (res is FlowAnalyzerResult)
                        {
                            if (firstErrorResult)
                            {
                                model.Max_Error = (res as FlowAnalyzerResult).PersentageOfError.ToString("0.##");
                                model.Error__mBr = (res as FlowAnalyzerResult).MaxLocalError.ToString();
                                model.Trend = (res as FlowAnalyzerResult).Trend;
                                firstErrorResult = false;
                            }
                            else
                            {
                                model.MaxError2 = (res as FlowAnalyzerResult).PersentageOfError.ToString("0.##");
                                model.Error2 = (res as FlowAnalyzerResult).MaxLocalError.ToString();
                                model.Trend2 = (res as FlowAnalyzerResult).Trend;
                            }
                        }
                    }
                   
                    model.Test_result = pass ? "Pass" : "Fail";
                    model.Eng_Recommendations = "-";
                    model.Last_Action = "-";
                    
                    threadCharacteristicsExelModels.Add(model);

                    writer = new ExcelWriter(file);
                    writer.WriteData(threadCharacteristicsExelModels, "Data");

                    writer.Dispose();
                    writer = null;

                }
                catch (Exception ex)
                {
                    InvokeUI(() =>
                    {
                        MessageBox.Show("An error occurred while trying to save results in file DispensersData.xlsx. Error" + ex.Message,
                                          "Warning",
                                          MessageBoxButton.OK,
                                          MessageBoxImage.Warning);
                    });
                }
                finally
                {
                    IsFree = true;

                    if (reader != null)
                        reader.Dispose();
                    if (writer != null)
                        writer.Dispose();
                    
                }
            });

        }
        #endregion

        #region CompareResults

        private void Compareresults(object obj)
        {
            //List<string> names, List<AnalyzerResultBase> results
            CompareResultsDlg resultsdlg = new CompareResultsDlg( ResultsToCompare);
            resultsdlg.Owner = System.Windows.Application.Current.MainWindow;
            resultsdlg.ShowDialog();

            AddToComare = false;
            ResultsToCompare.ToList().ForEach(x => x.RemoveCompareResultEvent -= OnCompareResultsChanged);
            ResultsToCompare.Clear();
            CompareCommand.RaiseCanExecuteChanged();
        }

        private bool CanCompareresults(object arg)
        {
            return ResultsToCompare.Count > 1;
        }

        private void OnAddToCompareResults(bool add)
        {
            if(add)
            {
                if (ResultsToCompare.Count == 3)
                {
                    ResultsToCompare.RemoveAt(0);
                }
                ResultsToCompare.Add( new CompareResultModel(new EventHandler(OnCompareResultsChanged)) { Result= AnalyzerResults[0] as AnalyzerResultBase, IsAddedResult = true, ResultName = Path.GetFileNameWithoutExtension(FileName)});
                
            }
            if(add == false )
            {
                if (ResultsToCompare.Count > 0)
                {
                    ResultsToCompare[ResultsToCompare.Count - 1].RemoveCompareResultEvent -= OnCompareResultsChanged;
                    ResultsToCompare.RemoveAt(ResultsToCompare.Count - 1);
                }
            }
            CompareCommand.RaiseCanExecuteChanged();
        }

        public void OnCompareResultsChanged(object sender, EventArgs e)
        {
            CompareResultModel result = sender as CompareResultModel;
            if(result != null && result.IsAddedResult == false)
            {
                result.RemoveCompareResultEvent -= OnCompareResultsChanged;
                ResultsToCompare.Remove(result);
                CompareCommand.RaiseCanExecuteChanged();
            }
        }

        public bool CanSaveExel(object arg)
        {
            var analyzer = AnalysisService.GetAnalyzer(OpenFilePath);
            if (analyzer == null)
                return false;
            return AnalyzerResults.Count > 0 && analyzer is FlowAnalyser;
        }

        private void SaveExel()
        {
            if(!IsFree)
                return;

          // await  ExportRMLToExcel().ConfigureAwait(false);
            ExportFlowResultsToExcel();
        }

            #endregion
        }
}