<?php


namespace App\Model\Facades\Writers;


use App\Model\Entities\GameData\Studio;
use App\Model\Facades\Readers\StudioReader;
use App\Model\Services\StudioService;
use Throwable;

class StudioWriter extends BaseWriter
{
    /** @var StudioService */
    protected $studioService;
    /** @var  StudioReader */
    protected $studioReader;

    public function inject(StudioService $studioService, StudioReader $studioReader)
    {
        $this->studioService = $studioService;
        $this->studioReader = $studioReader;
    }

    /**
     * @param $name
     * @return Studio
     * @throws Throwable
     */
    public function createStudio($name)
    {
        try {
            $this->beginTransaction();
            $studio = $this->studioService->createStudio($this->getLoggedInUser(), $name);
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }

        return $studio;
    }

    public function editName($studio, string $name)
    {
        $studioEntity = $this->studioReader->validateStudio($studio);

        try {
            $this->beginTransaction();
            $studioEntity->setName($name);
            $studioEntity->setEditedBy($this->getLoggedInUser());
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }
    }

    public function editState($studio, $status)
    {
        $studioEntity = $this->studioReader->validateStudio($studio);

        try {
            $this->beginTransaction();
            $studioEntity->setState($status);
            $studioEntity->setEditedBy($this->getLoggedInUser());
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }
    }


}