<?php


namespace App\Model\Services;


use App\Model\Entities\Security\User;
use App\Model\Entities\Templates\BaseTemplate;
use App\Model\Interfaces\ICommonRecord;
use App\Model\Interfaces\ISite;
use App\Model\Interfaces\ITemplate;

class TemplateService extends BaseService
{
    /**
     * @param int $id
     * @param $repository
     * @return BaseTemplate|null
     */
    public function findTemplateById(int $id, $repository = BaseTemplate::class)
    {
        return $this->getRepository($repository)->find($id);
    }

    public function createTemplate($class, User $createdBy, ISite $site, string $name, string $description, ITemplate $parentTemplate = null) : ITemplate
    {
        /** @var BaseTemplate $template */
        $template = new $class($createdBy, $site);
        $template->setName($name);
        $template->setDescription($description);
        if ($parentTemplate !== null) {
            $template->setParentTemplate($parentTemplate);
        }

        $this->persist($template);
        return $template;
    }

    /**
     * @param string $repository
     * @param ISite $site
     * @return array
     */
    public function getTemplateSelectBoxPairs(string $repository, ISite $site) : array
    {
        $criteria = [];
        $criteria['state'] = ICommonRecord::ACTIVE;
        $criteria['site'] = $site;
        // State is not necessary as param. All templates implements ICommonRecord.
        return $this->getRepository($repository)->findPairs($criteria, 'name');
    }
}