<?php

namespace App\Http\Controllers;

use App\Http\Requests\CropSizeRequest;
use App\MediaRepository;
use App\Services\RemoveBg;
use Illuminate\Http\Request;
use Mtc\ContentManager\Http\Requests\MediaUploadRequest;
use Mtc\ContentManager\Http\Controllers\MediaController as MtcMediaController;
use Mtc\ContentManager\ImageSize;
use Mtc\MercuryDataModels\MediaUse;

class MediaController extends MtcMediaController
{
    /**
     * Process file upload
     *
     * @param Request $request
     * @return mixed
     */
    public function store(MediaUploadRequest $request)
    {

        if ($request->fileIsImage() && request()->input('removeBackground') == 'true') {
            (new RemoveBg())->handle($request->file('file'));
        }

        return parent::store($request);
    }

    public function cropMediaSize(CropSizeRequest $request, MediaUse $mediaUse, MediaRepository $repository)
    {
        $size = ImageSize::fromArray($request->input());

        $size_list = $mediaUse->allowed_sizes ?? [];
        $size_list[] = $size->getWidth() . 'x' . $size->getHeight();
        $mediaUse->update([
            'allowed_sizes' => $size_list
        ]);
        return $repository->createSize($mediaUse->media, $size);
    }
}
