<?php

#error_reporting(E_ALL);
#ini_set('display_errors', TRUE);
#ini_set('display_startup_errors', TRUE);

ini_set('display_errors', FALSE);
ini_set('display_startup_errors', FALSE);

include 'fonction.php';

require 'vendor/autoload.php';

$root = $_SERVER["DOCUMENT_ROOT"];

$directory = "/uploads/";

if(isset($_GET["file"])) {
    $file = $root.urldecode($_GET["file"]);
    $size = isset($_GET["size"]) ? $_GET["size"] : 100;
    if(file_exists($file)) {
        switch (font_type($file)) {
            case 'file-image':
                echo getThumbnail($file, $size);
                break;
            case 'file-video':
                $thumb = createThumbnail($file, 10);
                echo getThumbnail($thumb, $size);
                break;
            case 'file-pdf':
                // code...
                break;
            default:
                echo "Not image";
                break;

        }
        exit();
    }
    else {
        header("HTTP/1.1 400 File not Found");
        echo $file." not Found";
        exit();
    }
}

function createThumbnail(string $file, int $sec)
{
    $thumbnail = '/tmp/thumbnail.png';

    $ffmpeg = FFMpeg\FFMpeg::create();
    $video = $ffmpeg->open($file);
    $frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds($sec));
    $frame->save($thumbnail);

    return($thumbnail);
}


function getThumbnail(string $file, int $size)
{

    list($width, $height) = getimagesize($file);

    // Create an Imagick object
    $imagick = new Imagick($file);

    // Function to set the background color
    $imagick->setbackgroundcolor('rgb(0, 0, 0)');

    // Use thumbnailImage function
    $imagick->thumbnailImage($width*$size/$height, $size, true, true);
    header("Content-Type: image/jpg");

    // Display the output image 
    echo $imagick->getImageBlob();

}

?>
