<?php

namespace Comitium5\DesignerBundle\UseCase\Page;

use Comitium5\DesignerBundle\Model\Interfaces\LocaleInterface;
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, LocaleInterface $locale)
    {
        $page = $this
            ->pageRepository
            ->getPageFromOrigin($originPageId);

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

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

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

        return false;
    }

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

        return true;
    }

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

        return true;
    }
}
