<?php

namespace Comitium5\DesignerBundle\Publisher;

use Comitium5\DesignerBundle\Manager\View\ViewManager;
use Comitium5\DesignerBundle\Model\Interfaces\Page\PageInterface;
use Monolog\Logger;

/**
 * Class FrontPublisher
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Publisher
 */
class FrontPublisher
{
    const TWIG_NAMESPACE = '@Comitium';

    /**
     * @var Logger
     */
    private $logger;

    /**
     * @var string
     */
    private $frontPath;

    /**
     * @var ViewManager
     */
    private $viewManager;

    /**
     * FrontPublisher constructor.
     *
     * @param Logger $logger
     * @param ViewManager $viewManager
     * @param $frontPath
     */
    public function __construct(
        Logger $logger,
        ViewManager $viewManager,
        $frontPath
    ) {
        $this->logger = $logger;
        $this->viewManager = $viewManager;
        $this->frontPath = $frontPath;
    }

    /**
     * @param array $paths
     * @param PageInterface $page
     *
     * @throws \Exception
     */
    public function publish(array $paths, PageInterface $page)
    {
        $targetPath = $this->buildTargetPaths();

        foreach ($paths as $path => $content) {
            try {
                $this
                    ->viewManager
                    ->create(
                        $targetPath.$path,
                        $content,
                        $page
                    );
            } catch (\Exception $exception) {
                throw $exception;
            }
        }
    }

    /**
     * @param array $paths
     *
     * @throws \Exception
     */
    public function removeFiles(array $paths)
    {
        $targetPath = $this->buildTargetPaths();

        foreach ($paths as $path) {
            try {
                $this
                    ->viewManager
                    ->remove(
                        $targetPath.$path
                    );
            } catch (\Exception $exception) {
                throw $exception;
            }

        }
    }

    /**
     * @return mixed
     * @throws \Exception
     */
    public function buildTargetPaths()
    {
        return self::TWIG_NAMESPACE;
    }
}
