<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\MediaBundle\Glide;

use League\Glide\Server;

class GlideServer extends Server
{
    /**
     * @param array<string, mixed> $params
     */
    public function getCachePath($path, array $params = []): string
    {
        $customCallable = $this->getCachePathCallable();
        if (null !== $customCallable) {
            $boundCallable = \Closure::bind($customCallable, $this, static::class);

            return $boundCallable($path, $params);
        }

        $sourcePath = $this->getSourcePath($path);

        if ($this->sourcePathPrefix) {
            $sourcePath = mb_substr($sourcePath, mb_strlen($this->sourcePathPrefix) + 1);
        }

        $params = $this->getAllParams($params);
        unset($params['s'], $params['p']);
        ksort($params);

        $filename = pathinfo(basename($sourcePath), \PATHINFO_FILENAME);
        $cachedPath = $filename.'_'.dechex(crc32($sourcePath.'?'.http_build_query($params)));

        if ($this->groupCacheInFolders) {
            $cachedPath = $sourcePath.'/'.$cachedPath;
        }

        if ($this->cachePathPrefix) {
            $cachedPath = $this->cachePathPrefix.'/'.$cachedPath;
        }

        if ($this->cacheWithFileExtensions) {
            $pathInfo = pathinfo($path);
            $ext = $params['fm'] ?? ($pathInfo['extension'] ?? '');
            $ext = ('pjpg' === $ext) ? 'jpg' : $ext;
            $cachedPath .= '.'.$ext;
        }

        return $cachedPath;
    }
}
