<?php

namespace App\Livewire\Artist;

use Livewire\Component;
use Livewire\WithFileUploads;
use Spatie\Image\Image;
use Intervention\Image\Facades\Image as InterventionImage;
use ImageOptimizer;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rules\File;
use Illuminate\Http\RedirectResponse;
use Livewire\Attributes\Validate;
use Illuminate\Support\Facades\Log;
use App\Jobs\OptimizeAvatarJob;

class Avatar extends Component
{
    use WithFileUploads;

    public $avatar;

    public $x;
    public $y;
    public $width;
    public $height;

    public function render()
    {
        return view('livewire.artist.avatar');
    }

    public function save()
    {
        $disk = Storage::disk('static');
        $avatar = $this->avatar->store('avatars', 'static');
        Image::load($disk->path($avatar))
            ->manualCrop($this->width, $this->height, $this->x, $this->y)
            ->save();
        Image::load($disk->path($avatar))
            ->width(350)
            ->height(350)
            ->save();
        Log::info('Avatar: Optimizing ' . $disk->path($avatar));
        OptimizeAvatarJob::dispatchSync($disk->path($avatar));
        //ImageOptimizer::optimize($disk->path($avatar));
        auth()->user()->artists()->first()->update(compact('avatar'));
        $this->avatar = null;
        return redirect(request()->header('Referer'));
    }
}