<?php

namespace Comitium5\DesignerBundle\Manager\Layout;

use Comitium5\DesignerBundle\Factory\AbstractFactory;
use Comitium5\DesignerBundle\Helper\Utils;
use Comitium5\DesignerBundle\Manager\AbstractManager;
use Comitium5\DesignerBundle\Manager\Breakpoint\BreakpointManager;
use Comitium5\DesignerBundle\Model\Interfaces\Layout\LayoutBreakpointInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;

/**
 * Class LayoutBreakpointManager
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Manager\Layout
 */
class LayoutBreakpointManager extends AbstractManager
{
    /**
     * @var BreakpointManager
     */
    private $breakpointManager;

    /**
     * @param AbstractFactory $factory
     * @param ObjectRepository $repository
     * @param ObjectManager $objectManager
     * @param BreakpointManager $breakpointManager
     */
    public function __construct(
        AbstractFactory $factory,
        ObjectRepository $repository,
        ObjectManager $objectManager,
        BreakpointManager $breakpointManager
    ){
        $this->factory = $factory;
        $this->repository = $repository;
        $this->objectManager = $objectManager;
        $this->breakpointManager = $breakpointManager;
    }

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

        $dateFields = array('startAt', 'endAt');
        $specificFields = array('breakpoint', 'layout');
        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]);
                }
            }
        }

        $layoutBreakpoint->fromArray($data);
        if (!empty($breakpoint)) {
            $entity = $this->breakpointManager
                ->fromArray($breakpoint);
            $layoutBreakpoint->setBreakpoint($entity);
        }
        if (!empty($layout)) {
            $entity = $layoutManager
                ->fromArray($layout);
            $layoutBreakpoint->setLayout($entity);
        }

        return $layoutBreakpoint;
    }

    /**
     * @param LayoutBreakpointInterface $item
     * @return LayoutBreakpointInterface
     */
    public function cloneItem($item)
    {
        $entity = clone $item;

        $this->cloneHandler($entity, $item);
        $entity->setLayout(null);

        return $entity;
    }
}
