<?php


namespace Mehrab\Media\Services;


use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Mehrab\Media\Contracts\MediaServiceContract;
use Mehrab\Media\Models\Media;
use phpDocumentor\Reflection\Types\Self_;

class ImageFileService extends DefaultFileService implements MediaServiceContract
{

    private static $sizes = ['100','300','500'];

    public static function upload($file,$fileName,$dir) :array
    {

        $extension = strtolower($file->getClientOriginalExtension());
        $file->move(storage_path($dir), $fileName . '.' . $extension);
        $path = $dir . DIRECTORY_SEPARATOR . $fileName . '.' . $extension;

        return self::resize(storage_path($path),$dir,$fileName,$extension);

    }

    private static function resize($imag,$dir,$fileName,$extension)
    {

        $imag = Image::make($imag);
        $imags['original'] = $fileName .'.'. $extension;

        foreach (self::$sizes as $size) {
            $imags[$size] = $fileName . '_'.$size .'.' . $extension;
            $imag->resize($size, null, function ($aspect) {
                $aspect->aspectRatio();
            })->save(storage_path($dir) . $fileName . '_'.$size .'.' . $extension);
        }

        return $imags;

    }

    public static function getFileName(){
        return (static::$media->is_private ? "app.".DIRECTORY_SEPARATOR."private".DIRECTORY_SEPARATOR : "app".DIRECTORY_SEPARATOR."public".DIRECTORY_SEPARATOR) . self::$media->files['original'];
    }

    public static function thumb(Media $media)
    {
        $url = 'storage/' . $media->files['original'] ?? null;
        return url($url);
    }
}
