<?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\Type\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\Type as EntityType;

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

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


    /**
     *
     * @var \Sso\Webservices\ObjectBundle\Model\Request\Type\Add\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">'
            . '<Name required="true"/>'
            . '<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.');
        }

        // set typeAddIn
        $modelIn = $this->apiM->serializer()->deserialize($simpleXML->TypeType->saveXML(),
            'Sso\Webservices\ObjectBundle\Model\Request\Type\Add\Entity', 'xml');
        $this->validate($modelIn);
        $modelOut = $this->apiM->database()->webservice()->types()->getEntity();

        $this->typeORM = $this->apiM->mapper()->modelInToModelOut($modelIn, $modelOut);

        $this->saveTypeEntity();
    }

    /**
     *
     */
    public function saveTypeEntity()
    {
        $em = $this->apiM->database()->webservice()->types()->getEntityManager();
        $em->persist($this->typeORM);
        $em->flush($this->typeORM);

    }

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

}
