<?php

/**
 * Class Add
 *
 * 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  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\Webservices\ObjectBundle\Model\Request\Attribute\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\Attribute as EntityAttribute;
use Sso\Webservices\ObjectBundle\Model\Request\Attribute\Add\Entity\Attribute as ModelIn;

/**
 * Class Add
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\Webservices\ObjectBundle\Model\Request\Attribute\Add
 */
class Add
{
    /**
     * @var ApiManager
     */
    protected $apiM;

    /**
     * @var EntityAttribute
     */
    protected $attributeModel;

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

    /**
     * Returns a xml-string with allowed structure
     *
     * @return string
     */
    protected function _xmlAllowedElements()
    {
        return '<AttributeType required="true">'
            . '<Name required="true"/>'
            . '<Mandatory/>'
            . '<PossibleValues>'
            . '<Value multiple="true"/>'
            . '</PossibleValues>'
            . '<DefaultValue/>'
            . '<Translatable/>'
            . '<GroupId required="true"/>'
            . '</AttributeType>';
    }

    /**
     * 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->AttributeType->saveXML(),
            'Sso\Webservices\ObjectBundle\Model\Request\Attribute\Add\Entity\Attribute',
            'xml'
        );
        $this->validate($modelIn);

        $this->attributeModel = $this->checkAndSetModelOrm($modelIn);
        $this->apiM->database()->webservice()->attribute()->saveAttribute($this->attributeModel);
    }

    /**
     * @param ModelIn $modelIn
     * @return \Sso\Webservices\ObjectBundle\Entity\Attribute
     * @throws InvalidRecordException
     */
    public function checkAndSetModelOrm(ModelIn $modelIn)
    {
        $modelOrm = $this->apiM->database()->webservice()->attribute()->getAttributeModel();
        $modelOrm
            ->setName($modelIn->getName())
            ->setMandatory($modelIn->getMandatory())
            ->setPossibleValues($modelIn->getPossibleValues())
            ->setDefaultValue($modelIn->getDefaultValue())
            ->setTranslatable($modelIn->getTranslatable());

        $groupId = $modelIn->getAttributeGroupId();
        $attributeGroupEntity = $this->apiM->database()->webservice()->attributeGroup()->getAttributeGroupRepository()->find($groupId);

        if (null === $attributeGroupEntity) {
            $this->apiM->errors()->addError(new ExternalError('v001', 'attributeGroup id not found',
                'attributeGroup id not found', 'attributeGroup id ' . $groupId . ' not found'));
            throw new InvalidRecordException('attributeGroup not found');
        }

        $modelOrm->setAttributeGroup($attributeGroupEntity);

        return $modelOrm;
    }

    /**
     *
     * @return EntityAttribute
     */
    public function getAttributeModel()
    {
        return $this->attributeModel;
    }

    /**
     * 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;
    }
}
