<?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
     */
    #[\Override]
    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 ?? [];
            $dimensionString = $size->getDimensionString();
            if (!in_array($dimensionString, $size_list)) {
                $size_list[] = $dimensionString;
                $mediaUse->update([
                    'allowed_sizes' => $size_list
                ]);
            }
        }
        return $result;
    }

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