#! /usr/bin/env perl

#use strict;
#use warnings;
use Image::Magick;
use List::Util;
use utf8;
use Pg;
use CGI;
use LWP::UserAgent;
use HTTP::Request::Common qw(POST);
use JSON qw/encode_json decode_json/;
use Encode;
use JSON;
use URI::Escape;


#****設計********************
#画像読込
	#１列分
	#縦の枚数になったら
	#縦結合
	#→画像名を配列
#＊これを横列分

#配列の画像読込
	#横列分
	#横結合
#保存
#***************************

my $q = new CGI;

#設定
my $free_token = '205050.0af4afe.569118134bcc4602812ed96c327ad85b';

#param
my $sword =$q->param('sword');
my $tate =$q->param('tate');
my $yoko =$q->param('yoko');
my $mode =$q->param('mode');
my $flg =$q->param('flg');

my $totalNum = $tate * $yoko + 10;

#my $usersid = '296316';
#my $usersid = '205050';

#URL
my $searchurl = 'https://api.instagram.com/v1/tags/' . $sword . '/media/recent?access_token=' . $free_token . $maxidUrl;
my $picFromUidurl = 'https://api.instagram.com/v1/users/' . $sword . '/media/recent/?access_token=' . $free_token . $maxidUrl;


if ($mode){
	if ($flg == "tag"){
	&getPicUrl($searchurl);
}
elsif ($flg == "user") {
	&getPicUrl($picFromUidurl);
}

@jpg_1st_files = List::Util::shuffle @jpg_1st_files;

#カウンター初期値
my $count = 0;
my $num = 0;


#新規オブジェクト
my $image = Image::Magick->new;

foreach my $file (@jpg_1st_files) {
    $count = $count + 1;

    $image->Read($file);
	#横結合
	if ($count % $yoko == 0) {
        # 出力ファイル名（現在時刻）
        my $now = time;
		my $outFilePath = sprintf("./out/"."%d"."_"."%03d".".jpg", $now, $count);
		
		$num = $num + 1;
#		print "$count\n";

       # 結合オブジェクトを新規作成
        # (stack=>'false')で横に結合
        my $append = $image->Append(stack=>'false');
        $append->Write($outFilePath);
		
		push(@jpg_2nd_files, $outFilePath);
		
        $image = undef;
        $image = Image::Magick->new;
		last if ($num == $tate);
    }
}

$count = 0;

foreach my $file ( sort @jpg_2nd_files) {
	$count = $count + 1;

	$image->Read($file);

	#縦結合
	if ($count == $tate) {
        # 出力ファイル名（現在時刻）
        my $now = time;
		my $outFilePath = sprintf("./images/"."%d"."_"."%03d".".jpg", $now, $count);
		
		$img = $outFilePath;

		# 結合オブジェクトを新規作成
        # (stack=>'true')で縦に結合
        my $append = $image->Append(stack=>'true');
        $append->Write($outFilePath);
    }
}

}

print "Content-Type: text/html; charset=UTF-8\n\n";

print <<"END_OF_HTML";


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="X-UA-Compatible" content="IE=7" />
</head>
<body>
$picFromUidurl
<br>
$flg
<form action="http://gms.gdl.jp/~naoto/cgi-bin/unit.pl" method="post" style="margin-top:0em;margin-bottom:0em">
	縦
	<input type="text" class="text" name="tate" size="2" alt="SEARCH WORD" value="$tate" />
	横
	<input type="text" class="text" name="yoko" size="2" alt="SEARCH WORD" value="$yoko" />
	検索ワード
	<input type="text" class="text" name="sword" size="10" alt="SEARCH WORD" value="$sword" />
	<select name="flg" class="dropdown">
END_OF_HTML
            print "<option value=\"tag\"" . $selected2 . ">tag</option>\n";
			print "<option value=\"user\"" . $selected3 . ">user</option>\n";
print <<"END_OF_HTML";
	</select>
	<input type="submit" name="search" class="submit" value="Go!!" />
	<input type="hidden" name="mode" value="search" />
</form>
END_OF_HTML

if ($img) {
	print "<img src=\"";
	print $img;
	print "\" width=\"" . $yoko . "00\" height=\"" . $tate . "00\">";
}

print <<"END_OF_HTML";
</body>
</html>
END_OF_HTML

exit 0;

#引数：jsonを得られるURL
sub getPicUrl{
	my $getUrl = shift @_;
	my $request = HTTP::Request->new(GET => $getUrl);
		$request->referer($referer);
	my $ua = LWP::UserAgent->new;
	my $response = $ua->request($request);

	if ($response->is_success) {
		my $picJson = $response->content;
		my $picFromJson = from_json($picJson);

		for ($i=0;$i <= 20;$i++){
			#image情報
			my $pImage = $picFromJson->{'data'}[$i]->{"images"}->{"standard_resolution"}->{"url"};
			#last if (!$pImage);
			if ($pImage){
			push(@jpg_1st_files, $pImage);
			$showCount++;
			}
		}
		$next_max_id = $picFromJson->{'pagination'}->{'next_max_id'};
		$nextUrl = $picFromJson->{'pagination'}->{'next_url'};
		if ($next_max_id){
			if($showCount < $totalNum){
			&getPicUrl($nextUrl);
			}
			else {
				if ($sword){$swordurl = "&sword=" . $sword;}
				else {$swordurl = "";}
				if ($usersid){$nextUsersPic="&usersid=" . $usersid;}
				else {$nextUsersPic = "";}
			}
		}
	}
else {
	warn 'Failed to request to WEB API.', "\n";
	}
}
