<?php

/**
 * Class Show
 *
 * 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\Update;

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\Update\Attribute as ModelIn;

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

    /**
     * @var ModelIn
     */
    protected $modelIn;

    /**
     * @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">'
            . '<Id required="true"/>'
            . '<Name/>'
            . '<Mandatory/>'
            . '<PossibleValues>'
            . '<Value multiple="true"/>'
            . '</PossibleValues>'
            . '<DefaultValue/>'
            . '<Translatable/>'
            . '<GroupId/>'
            . '</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.');
        }

        $this->modelIn = $this->apiM->serializer()->deserialize(
            $simpleXML->AttributeType->saveXML(),
            'Sso\Webservices\ObjectBundle\Model\Request\Attribute\Update\Attribute',
            'xml'
        );
        $this->validate($this->modelIn);

        $this->updateAttribute();
    }

    private function updateAttribute()
    {
        $attributeId = $this->modelIn->getId();
        $this->attributeModel = $this->apiM->database()->webservice()->attribute()->getAttributeById($attributeId);

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

        if (null != $this->modelIn->getName()) {
            $this->attributeModel->setName($this->modelIn->getName());
        }

        $attributeGroupId = $this->modelIn->getAttributeGroupId();
        if (null != $attributeGroupId) {
            $attributeGroupEntity = $this->apiM->database()->webservice()->attributeGroup()->getAttributeGroupById($attributeGroupId);
            if (null === $attributeGroupEntity) {
                $this->apiM->errors()->addError(new ExternalError('v001', 'attributeGroup id not found',
                    'attributeGroup id not found', 'attributeGroup id ' . $attributeGroupId . ' not found'));
                throw new InvalidRecordException('attributeGroup not found');
            }
            $this->attributeModel->setAttributeGroup($attributeGroupEntity);
        }

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

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