<?php

namespace Comitium5\DesignerBundle\Factory\Subsite;

use Comitium5\DesignerBundle\Entity\Subsite;
use Comitium5\DesignerBundle\Factory\Locale\LocaleFactory;
use Comitium5\DesignerBundle\Factory\NormalizerFactoryInterface;
use Comitium5\DesignerBundle\Factory\Site\SiteFactory;
use Comitium5\DesignerBundle\Model\Traits\DateTimeFactoryTrait;

/**
 * Class SubsiteFactory
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Factory\Subsite
 */
class SubsiteFactory implements NormalizerFactoryInterface
{
    use DateTimeFactoryTrait;

    /**
     * @param array $subsite
     *
     * @return Subsite
     */
    public function create(array $subsite)
    {
        $entity = new Subsite();

        $entity
            ->setId($subsite["id"])
            ->setUuid($subsite["uuid"])
            ->setLocale($subsite["locale"])
            ->setName($subsite["name"])
            ->setDescription($subsite["description"])
            ->setDomain($subsite["domain"])
            ->setAcronym($subsite["acronym"])
            ->setIsDefault($subsite["isDefault"])
            ->setColor($subsite["color"])
            ->setConfig($subsite["config"])
        ;

        $this
            ->setSite($entity, $subsite)
            ->setLocales($entity, $subsite)
            ->setDateTime($entity, $subsite)
        ;

        return $entity;
    }

    /**
     * @param Subsite $entity
     * @param array $subsite
     *
     * @return $this
     */
    private function setSite(Subsite $entity, array $subsite)
    {
        $factory = new SiteFactory();

        $siteEntity = $factory->create($subsite["site"]);

        $entity->setSite($siteEntity);

        return $this;
    }

    /**
     * @param Subsite $entity
     * @param array $subsite
     *
     * @return $this
     */
    private function setLocales(Subsite $entity, array $subsite)
    {
        $factory = new LocaleFactory();

        $locales = [];

        foreach ($subsite["locales"] as $locale) {
            $localeEntity = $factory->create($locale);

            $locales[] = $localeEntity;
        }

        $entity->setLocaleDomains($locales);

        return $this;
    }
}
