#!/usr/bin/perl -w

use strict;

# todo: import vimeo as well

my $thumbdir = "./thumbs/";
my $prod_thumbs = "./movie_thumb/";

# from existing db
my $start = 5; # get this number from database

# https://www.youtube.com/watch?v=-8Y09vrux2Y
# https://i.ytimg.com/vi/IZN8KrZmvls/hqdefault.jpg
open(LIST, ">movies.csv");

foreach my $series (readpipe("ls *.txt")) {
	chop $series;
	warn $series;

	foreach my $line (readpipe("cat $series")) {
		chop $line;
		warn $line;

		$line =~ /.*\/(.*?)$/;
		my $uid = $1;
		next if not $uid;

# 1. get metadata
		if (!-f "./meta/$uid.txt") {
			system ("youtube-dl --get-id --get-description --get-thumbnail --get-duration -eq  $line > './meta/$uid.txt'");
		}
		my $metadata = readpipe("cat './meta/$uid.txt'");
		my @metadata = split/\n/,$metadata;
		my $title = shift @metadata;
		my $id = shift @metadata;
		my $thumb = shift @metadata;
		my $duration = pop @metadata;
		$metadata = join(" | ", @metadata);
		$metadata =~ s/\n//g;
		
		my $cat = 5;	# teater
			$cat = 6 if $series =~ /lgl/;	# lutke

		if (-f "$thumbdir.$id.png") {
			system ("mv '$thumbdir.$id.png' '$thumbdir$id.png'");	
			system ("mv '$thumbdir.$id-source.jpg' '$thumbdir$id-source.jpg'");	
			system ("mv '$thumbdir.$id-l.png' '$thumbdir$id-l.png'");	
		}

# 2. get thumbnails
		if (!-f "$thumbdir$id.png") {
			system("wget -O '$thumbdir$id-source.jpg' '$thumb'");
			system("convert -resize 1000x600 '$thumbdir$id-source.jpg' '$thumbdir$id-l.png'");
			system("convert -resize 500x300 '$thumbdir$id-source.jpg' '$thumbdir$id.png'");
		}

# 3. outputs ready for import

# | movie_id | title | description_short | description_long | year | rating | genre_id | director | actors | featured | kids_restriction | url | trailer_url | duration |

		warn join("\t",$start,$id,$title,$thumb,$duration,$metadata)."\n" if $title;
		print LIST join("\t", $start, $title, $metadata, $metadata, 2020, 3, $cat, 4, "[2]", 0, 0, $line, $line, $duration)."\n";

# 4. copy thumb to production dir
#		system ("cp $thumbdir$id.png $prod_thumbs$start.png");
		system ("convert $thumbdir$id.png $prod_thumbs$start.jpg");

	    $start++;
	    
	    #exit 0;
	}
}
close LIST;