<?php


namespace App\Model\Facades\Writers;


use App\Model\Facades\Readers\PublisherReader;
use App\Model\Services\PublisherService;
use Throwable;

class PublisherWriter extends BaseWriter
{
    /** @var PublisherService */
    protected $publisherService;
    /** @var  PublisherReader */
    protected $publisherReader;

    public function inject(PublisherService $publisherService, PublisherReader $publisherReader)
    {
        $this->publisherService = $publisherService;
        $this->publisherReader = $publisherReader;
    }

    public function createPublisher(string $name)
    {
        try {
            $this->beginTransaction();
            $publisher = $this->publisherService->createPublisher($this->getLoggedInUser(), $name);
            $this->commit();
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }

        return $publisher;
    }

    public function editName($publisher, string $newName)
    {
        $publisherEntity = $this->publisherReader->validatePublisher($publisher);

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

    public function editState($publisher, string $newState)
    {
        $publisherEntity = $this->publisherReader->validatePublisher($publisher);

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