<?php

namespace Comitium5\DesignerBundle\UseCase\Page;

use Comitium5\DesignerBundle\Model\Interfaces\Page\DesignerPageInterface;
use Comitium5\DesignerBundle\Model\Interfaces\Page\PagePublisherInterface;
use Comitium5\DesignerBundle\Model\Interfaces\Page\PageRepositoryInterface;
use Comitium5\DesignerBundle\Publisher\Page\PagePublisher;

/**
 * Class ChangeStatePageUseCase
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\UseCase\Page
 */
class ChangeStatePageUseCase
{
    const PUBLISHED   = 1;
    const UNPUBLISHED = 2;

    /**
     * @var PageRepositoryInterface
     */
    private $pageRepository;

    /**
     * @var PagePublisher
     */
    private $pagePublisher;

    /**
     * ChangeStatePageUseCase constructor.
     *
     * @param PageRepositoryInterface $pageRepository
     * @param PagePublisherInterface $pagePublisher
     */
    public function __construct(PageRepositoryInterface $pageRepository, PagePublisherInterface $pagePublisher)
    {
        $this->pageRepository = $pageRepository;
        $this->pagePublisher  = $pagePublisher;
    }

    /**
     * @param $originPageId
     * @param $state
     *
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function __invoke($originPageId, $state)
    {
        $page = $this
            ->pageRepository
            ->getPageFromOrigin($originPageId);

        if ($page instanceof DesignerPageInterface === false) {
            return false;
        }

        if ($state === self::PUBLISHED) {
            return $this->publishPage($page);
        }

        if ($state === self::UNPUBLISHED) {
            return $this->unPublishPage($page);
        }

        return false;
    }

    /**
     * @param DesignerPageInterface $page
     *
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function publishPage(DesignerPageInterface $page): bool
    {
        $this
            ->pagePublisher
            ->publish($page);

        return true;
    }

    /**
     * @param DesignerPageInterface $page
     *
     * @return bool
     * @throws \Exception
     */
    private function unPublishPage(DesignerPageInterface $page): bool
    {
        $this
            ->pagePublisher
            ->unPublish($page);

        return true;
    }
}
