<?php

/**
 * Request Type Update
 *
 * 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
 * @link       http://www.life-style.de
 */

namespace Sso\Webservices\ObjectBundle\Model\Request\Type\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\Type as EntityType;

/**
 * Request Type Update
 *
 * @copyright  2015 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */
class Update
{

    /**
     *
     * @var ApiManager
     */
    protected $apiM;


    /**
     *
     * @var \Sso\Webservices\ObjectBundle\Model\Request\Type\Update\Entity
     */
    protected $helperModel;

    /**
     *
     * @var EntityType
     */
    protected $typeORM;


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

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

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

        $requestModel = $this->apiM->serializer()->deserialize($simpleXML->TypeType->saveXML(),
            'Sso\Webservices\ObjectBundle\Model\Request\Type\Update\Entity', 'xml');
        $this->validate($requestModel);

        $this->typeORM = $this->apiM->database()->webservice()->types()->getTypeRepository()->find($requestModel->getId());

        $this->saveTypeEntity($requestModel);
    }

    /**
     * @param Entity $requestModel
     */
    public function saveTypeEntity(Entity $requestModel)
    {
        if (!$this->typeORM) {
            $this->apiM->errors()->addError(new ExternalError('t001', 'Type not found', 'Type not found',
                'Type not found'));
            throw new InvalidRecordException('Type not found');
        }

        if ($requestModel->getName() != null) {
            $this->typeORM->setName($requestModel->getName());
        }
        if ($requestModel->getTypeOrder() !== null) {
            $this->typeORM->setTypeOrder($requestModel->getTypeOrder());
        }

        $em = $this->apiM->database()->webservice()->types()->getEntityManager();
        $em->flush();
    }

    /**
     *
     * @return EntityType
     */
    public function getTypeModel()
    {
        return $this->typeORM;
    }

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

}
