package ResultGraph;

use strict;
use warnings;
use vars qw(@ISA);

@ISA=qw(Wx::Frame size_distribution);

use Wx qw(:everything);
use Wx::Event qw(EVT_CLOSE EVT_PAINT);

use PDL;
use PDL::Core;
use PDL::Math;
use PDL::Primitive;
use PDL::Complex;

use File::Spec;

# Parameters: title, position, size
sub new {
    my( $class ) = shift;
    # now we are calling the base class constructor
    my( $this ) = $class->SUPER::new( undef, -1, $_[0], $_[1], $_[2], $_[3] );
    size_distribution->new($this); # call constructor of parent

    # May not really be necessary, but anyway :
    EVT_CLOSE( $this, \&OnClose );

    Wx::InitAllImageHandlers();
    # This frame only displays the graph. Define a Paint event that performs
    # the drawing of the bitmap
    EVT_PAINT($this, sub {
      my $png_file = File::Spec->catfile( File::Spec->curdir(), 'result.png');
      # since here you are handling a paint event, you *MUST*
      # use a PaintDC      
      $this->{dc} = Wx::PaintDC->new( $this );
      $this->{dc}->BeginDrawing();
      my $bmp = Wx::Bitmap->new( $png_file,wxBITMAP_TYPE_PNG);
      $this->{dc}->DrawBitmap( $bmp, 0, 0, 1 );
      $this->{dc}->EndDrawing();
    });
    $this->Fit();
    return $this;
}

sub Create_Graph {
  my ($this,$status) = @_;
  # Test OS and determine path to gnuplot executable
  my $path_to_gnuplot;
  #my $png_file = File::Spec->rel2abs(File::Spec->catfile( File::Spec->curdir(), 'result.png'),File::Spec->curdir());
  my $png_file = File::Spec->catfile( File::Spec->curdir(), 'result.png');
  if ($^O =~ 'Win32') {
    $path_to_gnuplot = File::Spec->catfile( 'gnuplot','pgnuplot.exe');
    # printf("Windows\n");
  }
  else {
    $path_to_gnuplot = File::Spec->catfile(File::Spec->rootdir, 'usr','bin','gnuplot');
  }
  my $tmpfile = "result.txt";
  open(TMP, ">$tmpfile") || die ("Cannot create temporary file\n");
  # Write results to temporary file
  $this->calculate_xo;
  #$this->calculate_q;
  # Find end of particle size distribution (end of declining slope)
  # (for more condensed display)
  my $i=$this->dQ->getdim("0")-1;
  do {
    $i--;
  } until ((($this->dQ_elem($i)>$this->dQ_elem($i+1)) && ($this->dQ_elem($i)>1e-5)) || $i==0);
  my $xmax; # = where the graph should end
  # if we found a declining slope, use its end position as xmax
  if ($this->dQ_elem($i+1)<=1e-5) {
    $xmax=$this->xm_elem($i+1);
  # otherwise use last element as xmax
  } else {
    $xmax=$this->xm_elem($this->xm->getdim("0")-1);
  }
  $xmax*=1e6;# scale from m to µm
  for(my $i=0; $i<$this->xo->getdim(0);$i++) {
    my $t1=$this->xo_elem("$i")*1e6; # Units: µm
    my $t2=$this->Q_elem("$i");
    print TMP ("$t1\t$t2");
    $t1= $this->xm_elem("$i")*1e6; # Units: µm
    $t2=$this->q_elem("$i")/1e3; # Units: 1/mm
    print TMP ("\t$t1\t$t2\n");
  }
  close TMP;
  # Plot data from temporary file
  my $PLOTCOMMAND="plot ";
  $PLOTCOMMAND= "$PLOTCOMMAND" . "\'$tmpfile\' using 1:2 axis x1y1 title \'Q3\'  with lines linestyle 1, \'$tmpfile\' using 3:4 axis x1y2 title \'q3\' with lines linestyle 2";

  # pipe data to gnuplot
#  open ( GNUPLOT, "$path_to_gnuplot");
  open ( GNUPLOT, ">result_commands");

  #| sed 's/0 1 0/0 0.752941 0/;s/0 0 1/0 0 0.752941/;s/1 0 1/0.752941 0 0.752941/;s/0 1 1/0.752941 0.752941 0/;s/1 1 0/0 0.752941 0.752941/'");

  print GNUPLOT << "gnuplot_Commands";
  set output '$png_file'
  set terminal png
  #eps enhance color solid "Times-Roman" 11
  set size 0.857, 0.680
  set key top left
  set key spacing 1.3
  set missing "-"
  set ytics nomirror
  set xtics nomirror
  #set logscale x
  set xrange [:$xmax]
  set yrange [0:1]
  set y2range [:]
  set ytics 0, 0.1
  set y2tics nomirror
  set xlabel "xm [mum]"
  set ylabel "Q"
  set y2label "q [1/mm]"
  set style line 1 linetype 1 pointtype 9 pointsize 1
  set style line 2 linetype 2 lw 1.5 pointtype 7 pointsize 1
  set style line 3 linetype 3 lw 1.5 pointtype 9 pointsize 1
  $PLOTCOMMAND
gnuplot_Commands

  close (GNUPLOT);
  my $a = system("$path_to_gnuplot result_commands");
  # Set Window size to graph size
  my $Image = Wx::Image->new($png_file,wxBITMAP_TYPE_PNG);
  $this->SetSize(-1,-1,$Image->GetWidth,$Image->GetHeight);
  # Show Frame
  $this->Show(1);
}

sub OnClose {
  my( $this, $event ) = @_;
  #Wx::MessageBox( 'OnClose: Closing', 'OnClose', wxOK, $this );
  #$event->Skip();
  $this->Destroy();
}


1;
