<?php


namespace App\Model\Facades\Writers;


use App\Model\Entities\GameData\Mmorpg\Region;
use App\Model\Facades\Readers\GameReader;
use App\Model\Facades\Readers\RegionReader;
use App\Model\Services\RegionService;
use Throwable;

class RegionWriter extends BaseWriter
{
    /** @var  GameReader */
    protected $gameReader;
    /** @var  RegionService */
    protected $regionService;
    /** @var  RegionReader */
    protected $regionReader;

    public function inject(RegionService $regionService, GameReader $gameReader, RegionReader $regionReader)
    {
        $this->regionService = $regionService;
        $this->gameReader = $gameReader;
        $this->regionReader = $regionReader;
    }

    public function createRegion($game, string $name, $apiIdentifier = null) : Region
    {
        $gameEntity = $this->gameReader->validateGame($game);

        try {
            $this->beginTransaction();
            $region = $this->regionService->createRegion($this->getLoggedInUser(), $gameEntity, $name, $apiIdentifier);
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }

        return $region;
    }

    public function editState($region, string $newState)
    {
        $regionEntity = $this->regionReader->validateRegion($region);

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

    public function editApiIdentifier($region, string $newIdentifier)
    {
        $regionEntity = $this->regionReader->validateRegion($region);

        try {
            $this->beginTransaction();
            $regionEntity->setApiIdentifier($newIdentifier);
            $regionEntity->setEditedBy($this->getLoggedInUser());
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }
    }
}