<?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());
        $result = $repository->createSize($mediaUse->media, $size);

        if (!empty($result)) {
            $size_list = $mediaUse->allowed_sizes ?? [];
            if (!in_array($size->getWidth() . 'x' . $size->getHeight(), $size_list)) {
                $size_list[] = $size->getWidth() . 'x' . $size->getHeight();
                $mediaUse->update([
                    'allowed_sizes' => $size_list
                ]);
            }
        }
        return $result;
    }

    public function getStats(MediaRepository $repository)
    {
        return response()->json($repository->getStats());
    }
}
