<?php

namespace Comitium5\DesignerBundle\Manager\Template;

use Comitium5\DesignerBundle\Factory\AbstractFactory;
use Comitium5\DesignerBundle\Helper\Utils;
use Comitium5\DesignerBundle\Manager\AbstractManager;
use Comitium5\DesignerBundle\Model\Interfaces\Template\TemplateGroupInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;

/**
 * Class TemplateGroupManager
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Manager\Template
 */
class TemplateGroupManager extends AbstractManager
{
    /**
     * @var ObjectManager
     */
    private $templateManager;

    /**
     * @param AbstractFactory  $factory
     * @param ObjectRepository $repository
     * @param ObjectManager    $objectManager
     * @param TemplateManager  $templateManager
     */
    public function __construct(
        AbstractFactory $factory,
        ObjectRepository $repository,
        ObjectManager $objectManager,
        TemplateManager $templateManager

    ) {
        $this->factory    = $factory;
        $this->repository = $repository;
        $this->objectManager = $objectManager;
        $this->templateManager = $templateManager;
    }

    /**
     * @param mixed $data
     * @return TemplateGroupInterface
     */
    public function fromArray($data)
    {
        try {
            $templateGroup = $this->find(
                !empty($data['id']) ? $data['id'] : 0
            );
        } catch (\Exception $e) {
            $templateGroup = $this->getFactory()->create();
        }

        $dateFields = array('createdAt', 'updatedAt');
        $specificFields = array();
        foreach (array_merge($specificFields, $dateFields) as $field) {
            if (isset($data[$field])) {
                if (in_array($field, $dateFields)) {
                    $data[$field] = Utils::getDateTime($data[$field]);
                } else {
                    $$field = $data[$field];
                    unset($data[$field]);
                }
            }
        }

        $templateGroup->fromArray($data);

        return $templateGroup;
    }
}
