<?php

namespace Comitium5\DesignerBundle\Manager\Breakpoint;

use Comitium5\DesignerBundle\Helper\Utils;
use Comitium5\DesignerBundle\Manager\AbstractManager;
use Comitium5\DesignerBundle\Model\Interfaces\AbstractFactoryInterface;
use Comitium5\DesignerBundle\Model\Interfaces\Breakpoint\BreakpointInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;

/**
 * Class BreakpointManager
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Manager\Breakpoint
 */
class BreakpointManager extends AbstractManager
{
    /**
     * @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 mixed $data
     * @return BreakpointInterface
     */
    public function fromArray($data)
    {
        try {
            $breakpoint = $this->find(
                !empty($data['id']) ? $data['id'] : 0
            );
        } catch (\Exception $e) {
            $breakpoint = $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]);
                }
            }
        }

        $breakpoint->fromArray($data);

        return $breakpoint;
    }
}
