#!/usr/bin/perl

use strict;
use warnings;
use POSIX qw(strftime);
my $current_time = time;
my $datehere = strftime("%Y-%m-%d-%H-%M", localtime($current_time));
my $datehere2 = strftime("%Y-%m-%d-%H", localtime($current_time));
my $minutes = strftime("%M", localtime($current_time));

my $debugon = 0;
my $file_path = "/home/superkuh/app_installs/idlerpg/questinfo.txt";
my $basemapfilepath = '/home/superkuh/www/newmap.png';
my $questmapfilepath = '/home/superkuh/www/questmap.png';
my $gifframesdir = '/home/superkuh/www/idlequests';
my $mp4archivedir = "$gifframesdir/mp4";
my $questgiffilepath = '/home/superkuh/www/quest.gif';
my $questmp4filepath = '/home/superkuh/www/tmpquest.mp4';
my $questmp4filepath2 = '/home/superkuh/www/quest.mp4';
my $musicargs = '-i /home/superkuh/www/yaketysax.mp3 -shortest -c:a libmp3lame -map 1:a:0';
# config for archive mp4 quest list html fragment
my $archivequestvideolistfilepath = '/home/superkuh/www/archivequests.html'; # set this to undef or "" to disable generation
my $webserverdomainandrelativepathtomp4s = 'http://idle.superkuh.com/idlequests/mp4';
my $posterformp4beforeload = 'http://superkuh.com/idlers.jpg';

my $questtext;
my $stage;
my $type1quest_s_time;
my $goal1x;
my $goal1y;
my $goal2x;
my $goal2y;
my $player1nick;
my $player1x;
my $player1y;
my $player2nick;
my $player2x;
my $player2y;
my $player3nick;
my $player3x;
my $player3y;
my $player4nick;
my $player4x;
my $player4y;
my $questype = 2; # only 2 has x,y coords for animating

#T setup a trade route through the mountains to the neighboring land of Qwok and arrange correspondence with their leader, Cuincey-Love Vikk'l
#Y 2
#S 2
#P 235 125 430 60
#P1 Kurenai 372 60
#P2 Superkuh 385 60
#P3 123DMWM 387 60
#P4 MrSlimeDiamond 360 60

#T locate the centuries-lost tomes of the grim prophet Haplashak Mhadhu
#Y 1
#S 1717848651
#P1 Evil_H4x
#P2 Gauldoth
#P3 scumola
#P4 mernisse

open my $fh, '<', $file_path or die "Cannot open $file_path: $!";
while (my $line = <$fh>) {
		if ($line =~ /T\s+(.+)/) {
			$questtext = $1;
		} elsif ($line =~ /^Y (\d)/) {
			# don't care
			# okay, looks like I actually have to care
			$questype = $1;
			print "quest type raw value: $questype\n" if $debugon;
		} elsif ($line =~ /^S (\d+)/) {
			my $sthing = $1;
			print "S raw value: $sthing\n" if $debugon;
			if ($questype == 2) {
				$stage = $sthing;
			} elsif ($questype == 1) {
				#$type1quest_s_time = $sthing;
				$type1quest_s_time = strftime("%Y-%m-%d %H:%M:%S", localtime($sthing));
				#$type1quest_s_time = duration($sthing);
			}	
		} elsif ($line =~ /^P (\d+) (\d+) (\d+) (\d+)/) {
        	$goal1x = $1;
        	$goal1y = $2;
        	$goal2x = $3;
        	$goal2y = $4;
		} elsif ($line =~ /P1 (\w+) (\d+) (\d+)/) {
        	$player1nick = $1;
        	$player1x = $2;
        	$player1y = $3;
		} elsif ($line =~ /P2 (\w+) (\d+) (\d+)/) {
        	$player2nick = $1;
        	$player2x = $2;
        	$player2y = $3;
		} elsif ($line =~ /P3 (\w+) (\d+) (\d+)/) {
        	$player3nick = $1;
        	$player3x = $2;
        	$player3y = $3;
		} elsif ($line =~ /P4 (\w+) (\d+) (\d+)/) {
        	$player4nick = $1;
        	$player4x = $2;
        	$player4y = $3;
		} 
#P1 Evil_H4x
#P2 Gauldoth
#P3 scumola
#P4 mernisse	
# handle type 1 quests and get playnicks	
		 elsif ($line =~ /P1 (\w+)/) {
        	$player1nick = $1;
		} elsif ($line =~ /P2 (\w+)/) {
        	$player2nick = $1;
		} elsif ($line =~ /P3 (\w+)/) {
        	$player3nick = $1;
		} elsif ($line =~ /P4 (\w+)/) {
        	$player4nick = $1;
		}   
		
		       
}      
close $fh;   

print "quest: $questtext\n";
print "stage: $stage\n";
print "quest type: $questype\n";
print "goal1: $goal1x,$goal1y\n";
print "goal1: $goal2x,$goal2y\n";
print "P1: $player1nick ($player1x,$player1y)\n";    
print "P2: $player2nick ($player2x,$player2y)\n";    
print "P3: $player3nick ($player3x,$player3y)\n";    
print "P4: $player4nick ($player4x,$player4y)\n";  
        
my $questers = "Questers: $player1nick, $player2nick, $player3nick, $player4nick";        

###
if (!defined $questtext) {
	print "Quest ended or no current quests. Maybe making movie but definitely exiting...\n";
	# do something to append the text "QUEST OVER" like,
	`convert $questmapfilepath -gravity NorthWest -pointsize 50 -fill red -stroke black -draw "text 100,200 'QUEST OVER'" $questmapfilepath`; 	
 	# save the current gif and delete the frames
 	#`cp $questmapfilepath $gifframesdir/$datehere-frame.png`;
 	# make a final movie before deleting the frames if frames actually exist
 	my @files = glob "$gifframesdir/*-frame.png";
	makethemovie() if (@files); # so only the first time the script is called after the quest ends will return true
	generatehtmlforarchivequestlist() if $archivequestvideolistfilepath;
 		
 	#`rm $gifframesdir/*-frame.png`;
 	unlink glob "$gifframesdir/*-frame.png";
 	#`cp $questgiffilepath $gifframesdir/$datehere2-quest.gif` unless -e "$gifframesdir/$datehere2-quest.gif";
 	`cp $questmp4filepath2 $mp4archivedir/$datehere2-quest.mp4` unless -e "$mp4archivedir/$datehere2-quest.mp4";
	exit; # have to exit so time isn't wasted trying to make mp4 animations with ffmpeg after if loop
} else {
	$questtext =~ s/'/\\\'/g; # escape apostrophes for imagemagick
	$questtext =~ s/\b(.{1,46}\s)\b(?=\w.{9})/$1\n/g; # line breaks, but not on words and only long ones simplified
	my $newline_count = $questtext =~ tr/\n//;
	$questtext =~ s/\n(?!.*\n)//g if ($newline_count > 1); # remove all but the first \n because I'm a hack
	$questtext = ucfirst($questtext);

	if ($questype == 2) {
		# good default with Questers text in black at bottom with nicks
		`convert $basemapfilepath -stroke black -pointsize 30 -gravity NorthWest -draw "text $goal1x,$goal1y 'Quest 1'" -draw "text $goal2x,$goal2y 'Quest 2'" -pointsize 18 -fill red -stroke red -draw "text $player1x,$player1y '$player1nick'" -fill blue -stroke blue -draw "text $player2x,$player2y '$player2nick'" -fill green -stroke green -draw "text $player3x,$player3y '$player3nick'" -fill purple -stroke purple -draw "text $player4x,$player4y '$player4nick'" -stroke black -pointsize 10 -draw "text 10,50 '$questtext'" -stroke black -pointsize 10 -draw "text 5,480 '$questers'" $questmapfilepath`;	
	} elsif ($questype == 1) {
		print "qt: $questtext\n" if $debugon;
		`convert $basemapfilepath -gravity NorthWest -stroke black -pointsize 20 -draw "text 20,250 '$questtext'" -stroke black -pointsize 15 -draw "text 5,470 '$questers'" -pointsize 30 -fill red -stroke black -draw "text 20,200 'Quest Ends: $type1quest_s_time'" $questmapfilepath`;
		exit; # don't make movies of this type.	
	}# $type1quest_s_time
}

#	generatehtmlforarchivequestlist() if $archivequestvideolistfilepath; # for tests


# save the frame to an archive to make a gif
print "saving quest png frame to $gifframesdir...\n" if $debugon;
`cp $questmapfilepath $gifframesdir/$datehere-frame.png`;
# only make the mp4 every ~7 minutes (but sometimes 11 (..:56 to ..:07)
if ($minutes % 15 == 0 || $minutes == 0) {
	print "Making mp4 of progress...\n" if $debugon;
	#`convert -resize 250x250 -delay 30 -loop 0 $gifframesdir/*-frame.png $questgiffilepath`;
	# make it web browser seekable and optionally add benny hill music
	#`ffmpeg -y -i $questmp4filepath $musicargs -c copy -map 0 -movflags +faststart $questmp4filepath2`;	
	#`ffmpeg -y -i $questmp4filepath $musicargs -c:v copy -c:a libmp3lame -map 0:v:0 -map 1:a:0 -movflags +faststart $questmp4filepath2`;
	## good config before subroutine
	##`ffmpeg -y -framerate 30 -pattern_type glob -i '$gifframesdir/*-frame.png' -c:v libx264 -pix_fmt yuv420p '$questmp4filepath'`;
	##`ffmpeg -y -i $questmp4filepath $musicargs -c:v copy -map 0:v:0 -movflags +faststart $questmp4filepath2`;
	makethemovie();
	generatehtmlforarchivequestlist() if $archivequestvideolistfilepath;
}

sub makethemovie {
	print "Making mp4 of progress...\n" if $debugon;
	`cp $questmapfilepath $gifframesdir/$datehere-frame.png`;
	`ffmpeg -y -framerate 30 -pattern_type glob -i '$gifframesdir/*-frame.png' -c:v libx264 -pix_fmt yuv420p '$questmp4filepath'`;
	`ffmpeg -y -i $questmp4filepath $musicargs -c:v copy -map 0:v:0 -movflags +faststart $questmp4filepath2`;
}

sub duration { # return human duration of seconds
    my $s = shift;
    return "NA ($s)" if $s !~ /^\d+$/;
    return sprintf("%d day%s %02d:%02d:%02d",$s/86400,int($s/86400)==1?"":"s",
                   ($s%86400)/3600,($s%3600)/60,($s%60));
}

sub generatehtmlforarchivequestlist {
 	my @mp4files = glob "$mp4archivedir/*-quest.mp4";
 	
 	my %unique_elements;
	# Loop through the array and store unique elements in the hash
	foreach my $mp4filename (sort @mp4files) {
    	# Remove the last sequence of digits after the date
    	my $unique_key = $mp4filename;
    	$unique_key =~ s/-\d+-quest\.mp4$/-quest.mp4/;
    	# Store the element in the hash (but only the first one)
    	unless (exists $unique_elements{$unique_key}) {
    		$unique_elements{$unique_key} = $mp4filename;
    	}
	}
	# Create a new array with the unique elements
	my @unique_mp4files = values %unique_elements;
	#print foreach @unique_mp4files;
 	@mp4files = @unique_mp4files;
 	
 	
 	# for future to only show the 10 most recent
 	my $num_elements_to_remove = @mp4files - 10;
 	if (@mp4files > 16) {
		splice(@mp4files, 0, $num_elements_to_remove);
	}
 	
	my $archivevideoshtmlstring = "<div id=\"div_questmovies\">\n";
	foreach my $mp4filename (@mp4files) {
	    $mp4filename =~ s/.+\/(.+)/$1/;
		my $videostring = "<video class=\"playlistvideo floatleft\" controls id=\"$mp4filename\" preload=\"none\" width=\"500\" height=\"500\" poster=\"$posterformp4beforeload\">\n\t<source src=\"$webserverdomainandrelativepathtomp4s/$mp4filename\"></source>\n</video>\n\n";
		$archivevideoshtmlstring .= $videostring;
	}
	open(my $questlisthtml, '>', $archivequestvideolistfilepath) or die "Can't open $archivequestvideolistfilepath: $!";
	print $questlisthtml "$archivevideoshtmlstring";
	print $questlisthtml "<ul>\n\t<p>Recent Quests</p>\n";
	foreach my $mp4filename (sort @mp4files) {
		print $questlisthtml "\t<li><a href=\"#$mp4filename\">$mp4filename</a></li>\n";
	}
	print $questlisthtml "</ul>\n</div>\n<br clear=\"all\"\; />\n";
	close $questlisthtml or die "Can't close $questlisthtml: $!";
}
