package album;

use strict;
use utf8;
use Mojo::Base 'Mojolicious::Controller';
use myconstant;
use Imager;

my $cons       = myconstant->new();
my $imagedir   = $cons->{imagedir};
my $img        = $cons->{img};
my $max_size   = $cons->{max_size};
my $img_size   = $cons->{img_size};
my $item_count = $cons->{item_count};
my $real       = 'public';

sub rotate {
    my ( $s, $c ) = @_;
    my $filename = $c->param('_name');
    if ( $filename ne '' ) {
        if ( $c->param('_action') =~ /^\d{1,3}$/ ) {
            system(
"/usr/bin/mogrify -rotate @{[$c->param('_action')]} $real/$img/$filename"
            );
            system(
"/usr/bin/mogrify -rotate @{[$c->param('_action')]} $real/$imagedir/$filename"
            );
        }
        elsif ( $c->param('_action') eq 'touch' ) {
            system("/usr/bin/touch $real/$img/$filename");
            system("/usr/bin/touch $real/$imagedir/$filename");
        }
        elsif ( $c->param('_action') eq 'rotated' ) {
            $s->rotated($c);
        }

    }
}
sub rotated{
    my ($s,$c) = @_;
    my @imgs = ();
    my $image = Imager->new(
                    file => "$real/$imagedir/".$c->param('_name')
                );
    push @imgs,$image;
    for(1..59){
        push @imgs,$image->rotate(
                        degrees => 360 - (0.1 * $_ * 60)
                    )->
                    crop(
                        width => $image->getwidth,
                        height=>$image->getheight
                    );
    }
    my $data;
    Imager->write_multi({
            data => \$data,
            type => 'gif',
            gif_loop =>0,
        },@imgs);
    $c->render(data => $data,format=> 'gif');
}

sub get_images {
    my $s     = shift;
    my $opt   = shift || '';
    my $st    = shift || 0;
    my $items = shift || $item_count;
    my @files = $s->images_select( $st, $item_count, $s->get_images_sort() );
    my $text  = join(
        "\n",
        map {
qq{ <a href="/onepic?_name=$_"><img src="/$imagedir/$_" $opt></img></a>}
        } @files
    );

    return $text;
}

sub get_images_sort {
    my $s = shift;
    opendir my $dh, "$real/$imagedir" or die "Can't open $real/$imagedir";
    my @files = map { $_->[0] }
      sort { $a->[1] <=> $b->[1] }
      map { [ $_, -M "$real/$imagedir/$_" ] }
      grep { !/(hide\.png|show\.png|arrow.*\.png|black\.png)/ }
      grep { -s "$real/$imagedir/$_" != 0 }
      grep ( /^[^.]/, readdir $dh );
    return @files;
}

sub images_select {
    my $s = shift;
    my ( $next, $item, @files ) = @_;
    my $i      = -1;
    my $st     = $next * $item;
    my @select = ();
  SELECT:
    for (@files) {
        $i++;
        next SELECT if $i < $st;
        last SELECT if ( $i >= ( $next + 1 ) * $item );
        push @select, $_;
    }
    return @select;
}

sub flick{
   my ($s,$r) = @_;
   my $flick = {
       "name" => "$img" . "/" . $s->get_next_image($r,$r->param('_count')),
       "_name" => $s->get_next_image($r,$r->param('_count')),
       "preload" => "$img" . "/" . $s->get_next_image($r,$r->param('_count')*3),
   };
   return $flick;
}
sub get_next_image{
   my $s = shift;
   my $r = shift;
   my $count = shift;
   my $file = $r->param('_name'); 
   $file =~ s|.*?([^/]+\.[a-zA-Z0-9]*)(\?.*)*$|$1|;
   my @files = $s->get_images_sort();
   my $i = $s->search_index($file,@files);
   $i += $count;
   $i -= ($#files + 1) if($i > $#files);
   my $img = $files[$i];
   return $img;
}

sub preload{
   my $s = shift;
   my $name = shift;
   my @files = get_images_sort();
   $name =~ s|.*?([^/]+\.[a-zA-Z]*)(\?.*)*$|$1|;
   my $i = $s->search_index($name,@files);
   my $text = "<script>\n";
   for my $j (1 .. 2){
       $text .= qq{\$('<img src="$img/$files[$i + $j]">');\n};
       $text .= qq{\$('<img src="$img/$files[$i - $j]">');\n};
   }
   $text .= "</script>\n";
   return $text;
}
sub search_index{
   my ($s,$item,@arry) = @_;
   my $i = 0;
   for(@arry){
     if($item eq $_){
       return $i;
     }
     $i++;
   }
   return;
}
   
sub up_load {
    my $s        = shift;
    my $uploads   = shift;
    my $filename;
    for my $upload (@{$uploads}){
        $filename = $upload->filename;
        $filename = $ENV{REMOTE_USER} . "_" . $upload->filename
           if ( $ENV{REMOTE_USER} );
        $upload->move_to("$real/$img/$filename");
        if($filename =~ /(.*)\.mp4/i){
            my $outfile = "$1_mp4.jpg";
            system("ffmpeg -i $real/$img/$filename -vframes 1 $real/$imagedir/$outfile");
            $filename = $outfile;
        }else{
            my $size = -s "$real/$img/$filename";
            if ( $size > $max_size ) {
                system(
                    "convert -resize @{[int($img_size / $size * 100)]}% $real/$img/$filename $real/$imagedir/$filename"
                );
            }  
            else {
                system("cp $real/$img/$filename $real/$imagedir/$filename");
            }
        }
    } 
    return $filename;
}

sub put_inner {
    my $s = shift;
    return $cons->{inner};
}

sub imgTag{
    my $s = shift;
	my $file = shift;
	my $text;
	if($file =~ /(.*)_mp4.jpg$/){
		$text = <<TAG_END;
    <br /><br /><br /><br /><br />
    <br /><br /><br /><br /><br />
    <div align="center">
	<video
		src="$img/$1.mp4"
		preload="none" 
        onclick="this.play();"
		poster="$imagedir/$file" 
		width="640"
		controls>
	<source src="$img/$1.mp4">
	</video>
    </div>
TAG_END
	}else{
		$text = <<TAG_END;
	<a href="$img/$file" id="bigimg">
		<img src="$img/$file?@{[(stat("$real/$img/$file"))[9]]}" width=100% name="img"></img>
	</a>
TAG_END
	}
	return $text;
}
1;

