<?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\ObjectValue\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\ObjectAttributeValue as EntityObjectValue;
use Sso\Webservices\ObjectBundle\Model\Request\ObjectValue\Update\Entity as ModelIn;
use Sso\Webservices\ObjectBundle\Database\Manager as ObjectDatabaseManager;

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

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

    /**
     * @var ObjectDatabaseManager
     */
    protected $objectDbM;

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

    /**
     * @var EntityObjectValue
     */
    protected $objectValueEntity;

    /**
     *
     * @param ApiManager $apiM
     */
    public function __construct(ApiManager $apiM)
    {
        $this->apiM = $apiM;
        $this->objectDbM = $this->apiM->getContainer()->get('object_database_manager');
    }

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

    /**
     * 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 helper model
        $this->helperModel = $this->apiM->serializer()->deserialize($simpleXML->ObjectValueType->saveXML(),
            'Sso\Webservices\ObjectBundle\Model\Request\ObjectValue\Update\Entity', 'xml');
        $this->validateEntity();

        $this->objectValueEntity = $this->objectDbM->respository()->objectAttributeValue()->find($this->helperModel->getId());
        $this->updateObjectValueEntity($this->helperModel);
    }

    /**
     * @param ModelIn $requestModel
     */
    public function updateObjectValueEntity(ModelIn $requestModel)
    {
        if (!$this->objectValueEntity) {
            $this->apiM->errors()->addError(new ExternalError('ov001', 'objectValue not found', 'objectValue not found',
                'objectValue not found'));
            throw new InvalidRecordException('ObjectValue not found');
        }

        if ($requestModel->getValue() != null) {
            // check attribute possible values
            $objectEntity = $this->objectDbM->respository()->objectAttributeValue()->find($requestModel->getId());
            $attributeEntity = $this->objectDbM->respository()->attribute()->find($objectEntity->getAttribute());
            $attributePossibleValues = $attributeEntity->getPossibleValues();
            if (!empty($attributePossibleValues) && !in_array($requestModel->getValue(), $attributePossibleValues)) {
                $this->apiM->errors()->addError(
                    new ExternalError('ov003', 'invalid value', 'invalid value',
                        'value must be one of: ' . implode(', ', $attributePossibleValues))
                );
                throw new InvalidRecordException('Invalid value');
            }

            $this->objectValueEntity->setValue($requestModel->getValue());
        }

        if ($requestModel->getLanguageCode() != null) {

            $languageEntity = $this->objectDbM->respository()->language()->find($requestModel->getLanguageCode());
            if (!$languageEntity) {
                $this->apiM->errors()->addError(new ExternalError('ov002', 'objectValueLanguage not found',
                    'objectValueLanguage not found', 'objectValueLanguage not found'));
                throw new InvalidRecordException('ObjectValueLanguage not found');
            }

            $this->objectValueEntity->setLanguage($languageEntity);
        }

        $this->objectDbM->data()->objectAttributeValue()->save($this->objectValueEntity);
    }

    /**
     *
     * @return EntityObjectValue
     */
    public function getObjectValueEntity()
    {
        return $this->objectValueEntity;
    }

    /**
     * @return ModelIn
     */
    public function getHelperModel()
    {
        return $this->helperModel;
    }

    /**
     * Validate entity
     *
     * @param array $validationGroups
     * @return bool
     */
    protected function validateEntity($validationGroups = null)
    {
        $errors = $this->apiM->validator()->validate($this->helperModel, $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;
    }

}
