<?php


namespace App\Model\Facades\Writers;


use App\Model\Entities\GameData\Platform;
use App\Model\Facades\Readers\PlatformReader;
use App\Model\Services\PlatformService;
use DateTime;
use Exception;
use Throwable;

class PlatformWriter extends BaseWriter
{
    /** @var PlatformService */
    protected $platformService;
    /** @var  PlatformReader */
    protected $platformReader;

    public function inject(PlatformService $platformService, PlatformReader $platformReader)
    {
        $this->platformService = $platformService;
        $this->platformReader = $platformReader;
    }

    public function createPlatform(string $name, DateTime $releasedOn) : Platform
    {
        try {
            $this->beginTransaction();
            $platform = $this->platformService->createPlatform($this->getLoggedInUser(), $name, $releasedOn);
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            throw $e;
        }

        return $platform;
    }

    public function editName($platform, string $newName)
    {
        $platformEntity = $this->platformReader->validatePlatform($platform);

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

    public function editReleasedOn($platform, DateTime $releasedOn)
    {
        $platformEntity = $this->platformReader->validatePlatform($platform);

        try {
            $this->beginTransaction();
            $platformEntity->setReleasedOn($releasedOn);
            $platformEntity->setEditedBy($this->getLoggedInUser());
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }
    }

    public function editState($platform, string $newState)
    {
        $platformEntity = $this->platformReader->validatePlatform($platform);

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

}