###RUN_PERL: #!/usr/bin/perl
#
# /mscha/frameaftertime
# mscha TaT frame
#
# Copyright (C) 2020, 2024  Balthasar Szczepański
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

use strict;
use utf8;
# use Encode::Locale ('decode_argv');
use Encode ('encode', 'decode');

###PERL_LIB: use lib /botm/lib/mscha
use botm_common (
	'HTTP_STATUS',
	'fail_method', 'fail_content_type',
	'read_header_env',
	'url_query_decode',
	'merge_settings'
);
use mscha_lib (
	'redirect',
	'get_tat_frame'
);

binmode STDIN,  ':encoding(UTF-8)';
binmode STDOUT, ':encoding(UTF-8)';
binmode STDERR, ':encoding(UTF-8)';
# decode_argv();

my $time = time();
srand ($time+$$);

my %http;
my %cgi;
my %cgi_post;
my %frame_info;

my $method;
my $frame;
my $mode;
my $embed_URL;

if ($ENV{'REQUEST_METHOD'} =~ /^(HEAD|GET|POST)$/) {
	$method = $1;
}
else{
	exit fail_method($ENV{'REQUEST_METHOD'}, ['GET', 'POST', 'HEAD']);
}

%http = read_header_env(\%ENV);
%cgi = url_query_decode($ENV{'QUERY_STRING'});

if ($method eq 'POST') {
	if ($http{'content-type'} eq 'application/x-www-form-urlencoded') {
		my %cgi_post = url_query_decode( <STDIN> );
		%cgi = merge_settings(\%cgi, \%cgi_post);
	}
	# multipart not supported
	else{
		exit fail_content_type($method, $http{'content-type'});
	}
}

if ($ENV{'PATH_INFO'} =~ /^\/([^\/]+)(\/(.+))?$/) {
	$frame = $1;
	$mode = lc($3);
} else {
	$frame = '1';
	$mode = '';
}

if ($cgi{'frameNo'} ne '') {
	$frame = $cgi{'frameNo'};
}
elsif ($cgi{'frame'} ne '') {
	$frame = $cgi{'frame'};
}

if ($cgi{'mode'} ne '') {
	$mode = lc($cgi{'mode'});
}
if ($mode !~ /^(orig|diff)$/) {
	$mode = '';
}

%frame_info = get_tat_frame($frame, $time);

if (($mode eq 'diff') && ($frame_info{'diffUrl'} eq '')) {
	$mode = '';
}

if (($mode eq '') && ($frame_info{'match'} eq 'downloadedUrl')) {
	$mode = 'orig';
}

if ($mode eq 'orig') {
	$embed_URL = $frame_info{'downloadedUrl'};
}
elsif ($mode eq 'diff') {
	$embed_URL = $frame_info{'diffUrl'};
}
else {
	$embed_URL = $frame_info{'tatUrl'};
}

redirect($method, $embed_URL, HTTP_STATUS->{'see_other'});
