<?php


namespace App\Model\Facades\Writers;


use App\Model\Entities\Game;
use App\Model\Entities\GameData\Mmorpg\Faction;
use App\Model\Facades\Readers\FactionReader;
use App\Model\Facades\Readers\GameReader;
use App\Model\Services\FactionService;
use Throwable;

class FactionWriter extends BaseWriter
{
    /** @var  GameReader */
    protected $gameReader;
    /** @var  FactionService */
    protected $factionService;
    /** @var  FactionReader */
    protected $factionReader;

    public function inject(FactionService $factionService, GameReader $gameReader, FactionReader $factionReader)
    {
        $this->factionService = $factionService;
        $this->gameReader = $gameReader;
        $this->factionReader = $factionReader;
    }

    /**
     * @param int|Game $game
     * @param string $name
     * @return Faction
     * @throws Throwable
     */
    public function createFaction($game, string $name) : Faction
    {
        $gameEntity = $this->gameReader->validateGame($game);

        try {
            $this->beginTransaction();
            $faction = $this->factionService->createFaction($this->getLoggedInUser(), $gameEntity, $name);
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }

        return $faction;
    }

    public function editName($faction, $newName)
    {
        $factionEntity = $this->factionReader->validateFaction($faction);

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