package Uploader::GUI::wxImagePreview;
use strict;
use base qw/Wx::Panel Class::Accessor::Fast/;
use Wx qw/
             wxDefaultPosition
             wxDefaultSize
             wxBG_STYLE_CUSTOM
             wxIMAGE_QUALITY_HIGH
         /;

__PACKAGE__->mk_accessors( 
    qw/
          image
          image_size
          caption
      / 
);
use Data::Dumper;
use Wx::Event qw/
   EVT_PAINT
   EVT_SIZE
/;

sub new {
    my( $class, $params ) = @_;
    my( $self ) = $class->SUPER::new(
        $params->{parentwnd},
        -1,
        wxDefaultPosition,
        wxDefaultSize,
    );

    $self->SetBackgroundStyle(wxBG_STYLE_CUSTOM);

    Wx::InitAllImageHandlers();

    EVT_SIZE($self, sub {
            my ( $this, $event ) = @_;
    
            $this->Refresh;
            $event->Skip();
        }
    );


  EVT_PAINT(
      $self, 
      sub { 
          my ( $this, $event ) = @_;

          my $dc = Wx::AutoBufferedPaintDC->new($this);
          if($this->image){
      
              my ($w, $h) = $this->GetSizeWH;
              my $p_prop = $w / $h;
      
              # calculation made to keep aspect           
              # ratio and maximize image size
      
              my $scale;
              my ($img_w, $img_h) = @{$this->image_size};
              my $img_prop = $img_w / $img_h;
      
              $scale = ($p_prop > $img_prop)
              ? ($h / $img_h)
              : ($w / $img_w);
      
              $scale = 1 if($scale > 1);
      
              my ($sw, $sh) = map({$_ * $scale} $img_w, $img_h);
              my $bmp = Wx::Bitmap->new($this->image->Scale($sw, $sh, wxIMAGE_QUALITY_HIGH));
              my $xoff = ($w - $sw) / 2;
              my $yoff = ($h - $sh) / 2;
              $dc->DrawBitmap($bmp, $xoff, $yoff, $dc->Clear ? 1:1);
          }
          else{
              $dc->Clear;
          }
      }
  );

  
  $self;
}


1;
