<?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\OptimizeArtistHeaderJob;

class Header extends Component
{
    use WithFileUploads;

    public $header;

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

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

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