<?php

/**
 *
 * @class Show
 * @author sb
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2015 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @link       http://www.life-style.de
 *
 */

namespace Sso\Webservices\ObjectBundle\Model\Request\AttributeGroup\Add;

use LifeStyle\Tools\WebserviceBundle\Error\Type\External as ExternalError;
use LifeStyle\Tools\WebserviceBundle\Validator\Xml as XmlValidator;
use LifeStyle\Tools\WebserviceBundle\Exception\InvalidRecordException;
use Sso\ApiBundle\Api\Manager as ApiManager;
use Sso\Webservices\ObjectBundle\Entity\AttributeGroup as EntityAttributeGroup;
use Sso\Webservices\ObjectBundle\Model\Request\AttributeGroup\Add\Entity\AttributeGroup as ModelIn;

/**
 * type add request model
 */
class Add
{

    /**
     *
     * @var Manager\Index
     */
    protected $apiM;

    /**
     *
     * @var EntityAttributeGroup
     */
    protected $attributeGroupModel;

    /**
     *
     * @param ApiManager $apiM
     */
    public function __construct(ApiManager $apiM)
    {
        $this->apiM = $apiM;
    }

    /**
     * Returns a xml-string with allowed structure
     *
     * @return string
     */
    protected function _xmlAllowedElements()
    {
        return '<AttributeGroupType required="true">'
            . '<Name required="true"/>'
            . '<Types>'
            . '<Type multiple="true">'
            . '<Id required="true"/>'
            . '</Type>'
            . '</Types>'
            . '</AttributeGroupType>';
    }

    /**
     * Init model
     *
     * @param \SimpleXMLElement $simpleXML
     */
    public function init(\SimpleXMLElement $simpleXML)
    {
        $validator = new XmlValidator();
        if (!$validator->validate($simpleXML, $validator->strToXml($this->_xmlAllowedElements()))) {
            $this->apiM->errors()->addErrors($validator->errors()->getErrors());
            throw new InvalidRecordException('Invalid xml elements.');
        }

        $modelIn = $this->apiM->serializer()->deserialize($simpleXML->AttributeGroupType->saveXML(),
            'Sso\Webservices\ObjectBundle\Model\Request\AttributeGroup\Add\Entity\AttributeGroup', 'xml');
        $this->validate($modelIn);

        $this->attributeGroupModel = $this->checkTypeIdsSetModelOrm($modelIn);
        $this->apiM->database()->webservice()->attributeGroup()->saveAttributeGroup($this->attributeGroupModel);
    }

    /**
     *
     * @param ModelIn $modelIn
     * @return \Sso\Webservices\ObjectBundle\Entity\AttributeGroup
     * @throws InvalidRecordException
     */
    public function checkTypeIdsSetModelOrm(ModelIn $modelIn)
    {
        $modelOrm = $this->apiM->database()->webservice()->attributeGroup()->getAttributeGroupModel();
        $modelOrm->setName($modelIn->getName());

        foreach ($modelIn->getType() as $model) {

            $typeEntity = $this->apiM->database()->webservice()->types()->find($model->getId());
            if (null === $typeEntity) {
                $this->apiM->errors()->addError(new ExternalError('aga001', 'type id not found', 'type id not found',
                    'type id ' . $model->getId() . ' not found'));
                throw new InvalidRecordException('Type not found');
            }

            if ($modelOrm->hasType($typeEntity->getId())) {
                $this->apiM->errors()->addError(
                    new ExternalError(
                        'aga002',
                        'Cannot connect the same type twice',
                        sprintf('Cannot connect the same type twice (%s)', $typeEntity->getId()),
                        sprintf('Cannot connect the same type twice (%s)', $typeEntity->getId())
                    )
                );
                throw new InvalidRecordException('Type not found');
            }

            $modelOrm->addType($typeEntity);
        }

        return $modelOrm;
    }

    /**
     *
     * @return EntityAttributeGroup
     */
    public function getAttributeGroupModel()
    {
        return $this->attributeGroupModel;
    }

    /**
     * Validate entity
     *
     * @param object $entity
     * @param array $validationGroups
     * @return bool
     */
    protected function validate($entity, $validationGroups = null)
    {
        $errors = $this->apiM->validator()->validate($entity, $validationGroups);
        foreach ($errors as $error) {
            list($errorCode, $shortMessage, $longMessage) = explode('##', $error->getMessage());
            $this->apiM->errors()->addError(new ExternalError('v001', $errorCode, $shortMessage, $longMessage));
        }
        if (0 < count($errors)) {
            throw new InvalidRecordException('Invalid xml values');
        }
        return true;
    }

}
