<?php

namespace Comitium5\DesignerBundle\Manager\View;

use Comitium5\DesignerBundle\Manager\AbstractManager;
use Comitium5\DesignerBundle\Model\Interfaces\AbstractFactoryInterface;
use Comitium5\DesignerBundle\Model\Interfaces\View\ViewCollectionInterface;
use Comitium5\DesignerBundle\Model\Interfaces\View\ViewInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;

/**
 * Class ViewManager
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Manager\View
 */
class ViewManager extends AbstractManager
{
    /**
     * ViewManager constructor.
     *
     * @param AbstractFactoryInterface $factory
     * @param ObjectRepository $repository
     * @param ObjectManager $objectManager
     */
    public function __construct(
        AbstractFactoryInterface $factory,
        ObjectRepository $repository,
        ObjectManager $objectManager
    ) {
        $this->factory       = $factory;
        $this->repository    = $repository;
        $this->objectManager = $objectManager;
    }

    /**
     * @param $name
     * @param $code
     * @param ViewCollectionInterface $entity
     *
     * @return array|mixed|void
     * @throws \Exception
     */
    public function create($name, $code, ViewCollectionInterface $entity)
    {
        $view = $this->findByName($name);

        $update = $view instanceof ViewInterface;

        if ($update === false) {
            $view = $this
                ->factory
                ->create();
        }

        $view
            ->setName($name)
            ->setContent($code);

        $entity->addView($view);

        return $update === true ? $this->update($view) : $this->save($view);
    }

    /**
     * @param $name
     *
     * @return array|mixed
     */
    public function remove($name)
    {
        $view = $this->findByName($name);

        return parent::remove($view);
    }

    /**
     * @param string $name
     *
     * @return object|null|ViewInterface
     */
    public function findByName($name)
    {
        return $this
            ->repository
            ->findOneBy(["name" => $name]);
    }

    /**
     * @param $name
     *
     * @return bool
     */
    public function exists($name)
    {
        return !empty($this->findByName($name));
    }
}
