<?php

namespace Comitium5\DesignerBundle\Twig\Loader;

use Comitium5\DesignerBundle\Manager\View\ViewManager;
use Comitium5\DesignerBundle\Model\Interfaces\View\ViewInterface;
use Twig\Error\LoaderError;
use Twig\Loader\LoaderInterface;
use Twig\Source;

/**
 * Class DatabaseLoader
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Twig\Loader
 */
class DatabaseLoader implements LoaderInterface
{
    /**
     * @var ViewManager
     */
    private $viewManager;

    /**
     * DatabaseLoader constructor.
     *
     * @param ViewManager $viewManager
     */
    public function __construct(ViewManager $viewManager)
    {
        $this->viewManager = $viewManager;
    }

    /**
     * @param string $name
     *
     * @return mixed|string
     * @throws LoaderError
     */
    public function getSource($name)
    {
        $view = $this->findView($name);

        if ($view instanceof ViewInterface) {
            return $view->getContent();
        }

        throw new LoaderError(sprintf(
            "Template with name %s not found in database",
            $name
        ));
    }

    /**
     * @param string $name
     *
     * @return string
     */
    public function getCacheKey($name)
    {
        return "db_twig_".$name;
    }

    /**
     * @param string $name
     * @param int $time
     *
     * @return bool
     */
    public function isFresh($name, $time)
    {
        /**
         * Check updated date of views, duplicates the amount of queries to database. To avoid that, we choose to return
         * always true because designer is always re-generating the content.
         *
         * $view = $this->findView($name);
         *
         * if ($view instanceof ViewInterface && $view->getUpdatedAt() instanceof \DateTime) {
         *      return $view->getUpdatedAt()->getTimestamp() < $time;
         * }
         *
         * return false;
         **/

        return false;
    }

    /**
     * @param $name
     *
     * @return ViewInterface|object|null
     */
    private function findView($name)
    {
        return $this
            ->viewManager
            ->findByName($name);
    }

    public function getSourceContext($name)
    {
        // TODO: Implement getSourceContext() method.
    }

    public function exists($name)
    {
        // TODO: Implement exists() method.
    }
}
