<?php

namespace App\Twig\Extensions;

use App\Base\Service\MediaFiles;
use App\Torrentio\Action\Result\GetTvShowOptionsResult;
use ChrisUllyott\FileSize;
use Twig\Attribute\AsTwigFilter;
use Twig\Attribute\AsTwigFunction;

class UtilExtension
{

    public function __construct(
        private readonly MediaFiles $mediaFiles,
    ) {}

    #[AsTwigFunction('uniqid')]
    public function uniqid(): string
    {
        return uniqid();
    }

    #[AsTwigFilter('truncate')]
    public function truncate(string $text)
    {
        if (strlen($text) > 300) {
            $text = substr($text, 0, 300) . '...';
        }
        return $text;
    }

    #[AsTwigFilter('filesize')]
    public function type(string|int $size)
    {
        return (new FileSize($size))->asAuto();
    }

    #[AsTwigFilter('strip_media_path')]
    public function stripMediaPath(string $path)
    {
        return str_replace(
            $this->mediaFiles->getBasePath() . DIRECTORY_SEPARATOR,
            '',
            $path
        );
    }

    #[AsTwigFilter('episode_id_from_results')]
    public function episodeId($result): ?string
    {
        if (!$result instanceof GetTvShowOptionsResult) {
            return null;
        }

        return "S". str_pad($result->season, 2, "0", STR_PAD_LEFT) .
            "E". str_pad($result->episode, 2, "0", STR_PAD_LEFT);
    }
}
