aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/MainWindowVM.cs
blob: 9981166e2fd0321a21113a3f245e90d7c7e749dd (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<
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Tango PMR Generator
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated. Do not modify!
// </auto-generated>
//------------------------------------------------------------------------------

syntax = "proto3";

@foreach (var import in Model.Imports)
{
    <div>
        import "@(import)";
    </div>
}

package @(Model.Package);
option java_package = "com.twine.@(Model.Package.ToLower())";

message @(Model.Name)
{

@for (int i = 0; i < Model.Properties.Count; i++)
{
<div>
   @(Model.Properties[i].Description != null ? ("//" + Model.Properties[i].Description) : "")
   @(Model.Properties[i].Repeated ? "repeated" : "") @(Model.Properties[i].Type) @(Model.Properties[i].Name) = @(i + 1);
</div>
}
}
'n229' href='#n229'>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 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
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 System.Threading;
using Tango.DispenserAnalyzer.UI.View;


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; }
        #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);

            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);
            }
        }
        #endregion
        
        #region Generate

        public bool CanGenerate()
        {
            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();
            }
        }

        /// <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);
                }
            });

        }
        #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();
            }
        }

        #endregion
    }
}