<?php

namespace Tricks\MediaLibraryOverrides\Traits;

use Illuminate\Support\Arr;
use Spatie\Image\Enums\Fit;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Tricks\MediaLibraryOverrides\ResponsiveImages\WidthCalculator\StaticWidthsCalculator;

trait HasResponsiveConversions
{
    use InteractsWithMedia;

    const MEDIA_CONVERSION_NUXT = 'webp';
    const MEDIA_CONVERSION_OG_IMAGE = 'ogImage';

    public function registerMediaConversions(Media $media = null): void
    {
        if ($media->mime_type === 'image/gif') {
            // Stop here to allow animated gifs
            return;
        }

        $this->addMediaConversion(static::MEDIA_CONVERSION_NUXT)
            ->nonOptimized()
            ->width(max(config('media-library.nuxt-screens', StaticWidthsCalculator::DEFAULT_NUXT_SCREENS)))
            ->withResponsiveImages()
            ->format('webp');

        if (defined('static::MEDIA_OG_IMAGE') && is_string(static::MEDIA_OG_IMAGE)) {
            $this->addMediaConversion(static::MEDIA_CONVERSION_OG_IMAGE)
                ->performOnCollections(static::MEDIA_OG_IMAGE)
                ->fit(Fit::Crop, 1200, 630)
                ->format('jpg');
        }
    }

    public function registerMediaCollections(): void
    {
        $collections = [];
        if (defined('static::MEDIA_COLLECTIONS')) {
            $collections = static::MEDIA_COLLECTIONS;
        } elseif (defined('static::MEDIA_IMAGE')) {
            $collections = [static::MEDIA_IMAGE];
        }

        foreach ($collections as $collection) {
            $this
                ->addMediaCollection($collection)
                ->withResponsiveImagesIf(static::shouldHaveResponsiveImages($collection));
        }
    }

    /**
     * @deprecated use getMediaUrlForImageData instead.
     */
    public function getMediaForImageData(string $collection, string $conversion = ''): string
    {
        $media = $this->getFirstMedia($collection);
        if (! $media) {
            return '';
        }
        return $this->getMediaUrlForImageData($media, $collection, $conversion);
    }

    public function getMediaUrlForImageData(Media $media, string $collection, string $conversion = ''): string
    {
        if (static::shouldHaveResponsiveImages($collection) || $media->hasResponsiveImages($conversion)) {
            $imageUrls = $media->getResponsiveImageUrls($conversion);
            return preg_replace('/_W\d+_H/', '_W___WIDTH____H', Arr::first($imageUrls));
        }

        // TODO: check if this needs to be done _before_ $media->hasResponsiveImages()
        if (! $media->hasGeneratedConversion($conversion)) {
            $conversion = '';
        }
        return $media->getUrl($conversion);
    }

    protected static function shouldHaveResponsiveImages(string $collection): bool
    {
        if (! defined('static::SKIP_RESPONSIVE_IMAGES_ON') || ! is_array(static::SKIP_RESPONSIVE_IMAGES_ON)) {
            return true;
        }
        return in_array($collection, static::SKIP_RESPONSIVE_IMAGES_ON) === false;
    }
}
