<?php

namespace App\Repositories\Core;

use Spatie\MediaLibrary\MediaCollections\Models\Media as MediaModel;

class Medias
{
    public static function getImage($model, $conversion = 'normal', $collection = 'images')
    {
        $img = $model->getMedia($collection)->first();

        return $img ? $img->getUrl($conversion) : false;
    }

    public static function getImages($model)
    {
        if (! $model) {
            return false;
        }
        $model->getMedia();
        foreach ($model->media as $key => $media) {
            $model->media[$key]['url'] = $media->getUrl();
        }

        return $model->media;
    }

    public static function storeImages($model, $files)
    {
        if ($files) {
            foreach ($files as $file) {
                self::storeImage($model, $file);
            }
        }
    }

    public static function storeImage($model, $file, $collection = 'images')
    {
        return $model->addMedia($file)->sanitizingFileName(function ($fileName) {
            return str_replace(['#', '/', '\\', ' '], '-', $fileName);
        })->toMediaCollection($collection);
    }

    public static function deleteImages($model, $collection = 'images')
    {
        $ret = $model->clearMediaCollection($collection);

        return true;
    }

    public static function deleteImage($model, $index)
    {
        $model->getMedia();
        $ret = $model->media[$index]->delete();

        return true;
    }

    public static function buildURL($image, $conversion = '')
    {
        return self::getPath($image).self::getConversion($image, $conversion);
    }

    public static function getPath($image)
    {
        $model = basename(str_replace('\\', '/', $image->model_type));

        return '/storage/'.$model.'/'.$image->collection_name.'/'.$image->id;
    }

    public static function getConversion($image, $conversion = '')
    {
        return $conversion ? '/conversions/'.$image->name.'-'.$conversion.'.jpg' : $image->file_name;
    }

    public static function getExtension($filename)
    {
        return '.'.pathinfo($filename, PATHINFO_EXTENSION);
    }

    public static function getImageSrc($image)
    {
        $media = self::resolveMedia($image);

        return $media ? $media->getUrl() : null;
    }

    public static function getThumbSrc($image)
    {
        return self::getSrcByType($image, 'thumb');
    }

    public static function getPreviewSrc($image)
    {
        return self::getSrcByType($image, 'preview');
    }

    public static function getNormalSrc($image)
    {
        return self::getSrcByType($image, 'normal');
    }

    public static function getZoomSrc($image)
    {
        return self::getSrcByType($image, 'zoom');
    }

    public static function getSrcByType($image, $type)
    {
        $media = self::resolveMedia($image);

        if ($media) {
            return $type ? $media->getUrl($type) : $media->getUrl();
        }

        return $image ? '/storage/'.$image['id'].'/conversions/'.self::getFilename($image, $type) : false;
    }

    public static function getFilename($image, $type = false)
    {
        $image['name'] = self::convertName($image['name']);

        return $image['name'].($type ? '-'.$type : '').self::getExtension($image['file_name']);
    }

    public static function convertName($name)
    {
        return str_replace(['#', '/', '\\', ' '], '-', $name);
    }

    protected static function resolveMedia($image): ?MediaModel
    {
        if ($image instanceof MediaModel) {
            return $image;
        }

        if (is_null($image)) {
            return null;
        }

        if (is_array($image)) {
            return self::hydrateMedia($image);
        }

        if (is_object($image)) {
            if ($image instanceof \ArrayAccess) {
                return self::hydrateMedia((array) $image);
            }

            $array = method_exists($image, 'toArray') ? $image->toArray() : (array) $image;

            return self::hydrateMedia($array);
        }

        $id = data_get($image, 'id');

        return $id ? MediaModel::query()->withoutGlobalScopes()->find($id) : null;
    }

    protected static function hydrateMedia(array $attributes): ?MediaModel
    {
        $id = data_get($attributes, 'id');

        if (! $id) {
            return null;
        }

        $media = new MediaModel();
        $media->forceFill($attributes);
        $media->exists = true;

        return $media;
    }
}
