<?php

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

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

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

    /**
     *
     * @var ApiManager
     */
    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">'
            . '<Guid/>'
            . '<ReferenceId/>'
            . '<TypeId/>'
            . '<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.');
        }

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

        if (null !== $requestModel->getGuid()) {
            $this->objectModel = $this->apiM->database()->webservice()->object()->find($requestModel->getGuid());
        } elseif (null !== $requestModel->getReferenceId()) {
            $this->objectModel = $this->apiM->database()->webservice()->object()->getObjectRepository()->findOneBy(['referenceId' => $requestModel->getReferenceId()]);
        } else {
            $this->apiM->errors()->addError(new ExternalError('o001', 'No identifier specified',
                'Please set Guid or ReferenceId.',
                'Please set Guid or ReferenceId in order to update a specific object.'));
            throw new InvalidRecordException('No identifier specified');
        }

        $this->updateObjectEntity($requestModel);
    }

    /**
     * @param Entity $requestModel
     */
    public function updateObjectEntity(Entity $requestModel)
    {
        if (!$this->objectModel) {
            $this->apiM->errors()->addError(new ExternalError('o001', 'object not found', 'object not found',
                'object not found'));
            throw new InvalidRecordException('Object not found');
        }

        $this->setRelationships($requestModel);

        if ($requestModel->getName() != null) {
            $this->objectModel->setName($requestModel->getName());
        }
        if ($requestModel->getActive() !== null) {
            $this->objectModel->setActive($requestModel->getActive());
        }
        if ($requestModel->getType() !== null) {
            $this->objectModel->setType($requestModel->getType());
        }
        // always update parentGuid
        $this->objectModel->setParent($requestModel->getParent());

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

    /**
     * @param Entity $object
     */
    public function setRelationships(Entity $object)
    {
        // Set type object
        if ($object->getTypeId()) {
            $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;
    }

}