<?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\Object\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\Object as EntityObject;

/**
 * Class Add
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\Webservices\ObjectBundle\Model\Request\Object\Add
 */
class Add
{

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

    /**
     *
     * @var EntityObject
     */
    protected $objectModel;

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

    /**
     * Returns a xml-string with allowed structure
     *
     * @return string
     */
    protected function _xmlAllowedElements()
    {
        return '<ObjectType required="true">'
            . '<ReferenceId required="true"/>'
            . '<TypeId required="true"/>'
            . '<ParentGuid/>'
            . '<Name/>'
            . '<Active/>'
            . '</ObjectType>';
    }

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

        if ($this->apiM->database()->webservice()->object()->getObjectRepository()->findBy(['referenceId' => $modelIn->getReferenceId()])) {
            $this->apiM->errors()->addError(new ExternalError('oa001', 'Could not add object', 'Duplicate ReferenceId!',
                'Could not add object. Duplicate ReferenceId!'));
            throw new InvalidRecordException('Could not add object');
        }

        $modelOut = $this->apiM->database()->webservice()->object()->getObjectModel();
        $this->objectModel = $this->apiM->mapper()->modelInToModelOut($modelIn, $modelOut);
        $this->apiM->database()->webservice()->object()->saveObject($this->objectModel);
    }

    /**
     *
     */
    public function setRelationships(Entity $object)
    {
        // Set type object
        $typeEntity = $this->apiM->database()->webservice()->types()->find($object->getTypeId());
        if (null === $typeEntity) {
            $this->apiM->errors()->addError(new ExternalError('v001', 'type not found', 'type not found',
                'type not found'));
            throw new InvalidRecordException('Type not found');
        }
        $object->setType($typeEntity);

        // Set parent object
        if ($object->getParentGuid()) {
            $parentEntity = $this->apiM->database()->webservice()->object()->find($object->getParentGuid());
            if (null === $parentEntity) {
                $this->apiM->errors()->addError(new ExternalError('v001', 'parent object not found',
                    'parent object not found', 'parent object not found'));
                throw new InvalidRecordException('Type not found');
            }
            $object->setParent($parentEntity);
        }
    }

    /**
     *
     * @return EntityObject[]
     */
    public function getObjectModel()
    {
        return $this->objectModel;
    }

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

}