<?php

namespace ProudNerds\Video\Tasks;

use ProudNerds\Video\ImageExtractor;
use ProudNerds\Video\VideoConverter;

class VideoTask implements QueueTask
{
    private $videoId;
    private $conversionLocation;
    private $screenshotLocation;

    public function __construct($videoId, $conversionLocation, $screenshotLocation)
    {
        $this->videoId = $videoId;
        $this->conversionLocation = $conversionLocation;
        $this->screenshotLocation = $screenshotLocation;
    }

    /**
     * Get the task ID
     * Should be a unique identifier
     *
     * @return string
     */
    public function getTaskId(): string
    {
        return 'video-' . $this->videoId;
    }

    /**
     * Execute the task
     *
     * @param callable $callback    Callback function to call after the task has been executed
     */
    public function execute(callable $callback)
    {
        echo "Processing task (may take a while): " . $this->getTaskId() . "\n";

        $videoFile = get_attached_file($this->videoId);
        echo "Original video file: " . $videoFile . "\n";
        echo "File exists: " . (file_exists($videoFile) ? 'yes' : 'no') . "\n";

        if (!file_exists($videoFile)) {
            echo "ERROR: Origineel videobestand niet gevonden.\n";
            $callback();
            return;
        }

        // Create the folder if it doesn't exist
        if (!file_exists($this->conversionLocation)) {
            echo "Creating directory: " . $this->conversionLocation . "\n";
            mkdir($this->conversionLocation, 0755, true);
        }

        // Extract screenshot
        echo "Extracting screenshot to: " . $this->conversionLocation . "\n";
        $imageExtractor = new ImageExtractor();
        $screenshot = $imageExtractor->extract($videoFile, $this->conversionLocation, $this->screenshotLocation);
        echo "Screenshot result: " . ($screenshot ? $screenshot : 'failed') . "\n";

        // Convert video
        echo "Starting video conversion...\n";
        $videoConverter = new VideoConverter();
        $result = $videoConverter->convert($videoFile, $this->conversionLocation);
        echo "Conversion result: " . ($result ? 'success' : 'failed') . "\n";

        // List files in conversion directory after conversion
        echo "Files in conversion directory after processing:\n";
        $files = glob($this->conversionLocation . '*');
        foreach ($files as $file) {
            echo "- " . basename($file) . " (" . filesize($file) . " bytes)\n";
        }

        // Call the callback function if it exists
        echo "Task completed: " . $this->getTaskId() . "\n";
        $callback();
    }
}
