<?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\ObjectValue\Add;

use Sso\Webservices\ObjectBundle\Entity\Object as ObjectEntity;
use Sso\Webservices\ObjectBundle\Entity\Language as LanguageEntity;
use Sso\Webservices\ObjectBundle\Entity\Attribute as AttributeEntity;
use Sso\Webservices\ObjectBundle\Entity\ObjectAttributeValue as ObjectAttributeValue;
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\Database\Manager as ObjectDbM;

/**
 * type add request model
 */
class Add
{
    /**
     * @var ApiManager
     */
    protected $apiM;

    /**
     * @var ObjectAttributeValue
     */
    protected $objectAttributeValue;

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

    /**
     *
     * @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">'
            . '<ObjectGuid required="true"/>'
            . '<ObjectValue required="true"/>'
            . '<LanguageCode required="true"/>'
            . '<AttributeId required="true"/>'
            . '</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.');
        }

        $modelIn = $this->apiM->serializer()->deserialize(
            $simpleXML->ObjectValueType->saveXML(),
            'Sso\Webservices\ObjectBundle\Model\Request\ObjectValue\Add\Entity\ObjectValue',
            'xml'
        );
        $this->validate($modelIn);
        $this->setRelationships($modelIn);

    }

    /**
     *
     * @param Entity\ObjectValue $objectValueIn
     * @throws InvalidRecordException
     */
    public function setRelationships(Entity\ObjectValue $objectValueIn)
    {
        //check the object 
        $objectEntity = $this->objectDbM->respository()->object()->find($objectValueIn->getObjectGuid());
        if (null === $objectEntity) {
            $this->apiM->errors()->addError(
                new ExternalError('v001', 'object not found', 'object not found', 'object not found')
            );
            throw new InvalidRecordException('Object not found');
        }

        // check language code
        $languageEntity = $this->objectDbM->respository()->language()->find($objectValueIn->getLanguageCode());
        if (null === $languageEntity) {
            $this->apiM->errors()->addError(
                new ExternalError('v001', 'language not found', 'language not found', 'language not found')
            );
            throw new InvalidRecordException('Language not found');
        }

        // check attribute id
        $attributeEntity = $this->objectDbM->respository()->attribute()->find($objectValueIn->getAttributeId());
        if (null === $attributeEntity) {
            $this->apiM->errors()->addError(
                new ExternalError('v001', 'attribute not found', 'attribute not found', 'attribute not found')
            );
            throw new InvalidRecordException('Attribute not found');
        }

        // check attribute possible values
        $attributePossibleValues = $attributeEntity->getPossibleValues();
        if (!empty($attributePossibleValues) && !in_array($objectValueIn->getObjectValue(), $attributePossibleValues)) {
            $this->apiM->errors()->addError(
                new ExternalError('v001', 'invalid value', 'invalid value',
                    'value must be one of: ' . implode(', ', $attributePossibleValues))
            );
            throw new InvalidRecordException('Invalid value');
        }

        // no check if object has attributeGroup and allowed to use this attribute
        $objectHasAttribute = false;
        foreach ($objectEntity->getType()->getAttributeGroups() as $attributeGroup) {
            if ($attributeGroup->getId() == $attributeEntity->getAttributeGroup()->getId()) {
                $objectHasAttribute = true;
                break;
            }
        }
        if (!$objectHasAttribute) {
            $this->apiM->errors()->addError(
                new ExternalError('v001', 'attribute not connected to object', 'attribute not connected to object',
                    'attribute not connected to object')
            );
            throw new InvalidRecordException('attribute not connected to object');
        }

        // ok everything went fine update or add object value
        if ($this->objectValueAlreadyExists($objectEntity, $attributeEntity, $languageEntity)) {
            $this->updateObjectValue($objectEntity, $attributeEntity, $languageEntity,
                $objectValueIn->getObjectValue());
        } else {
            $this->addObjectValue($objectEntity, $attributeEntity, $languageEntity, $objectValueIn->getObjectValue());
        }
    }

    /**
     * Checks if an attribute value has already been added to the requested object
     *
     * @param ObjectEntity $objectEntity
     * @param AttributeEntity $attributeEntity
     * @param LanguageEntity $languageEntity
     * @return bool
     */
    private function objectValueAlreadyExists(
        ObjectEntity $objectEntity,
        AttributeEntity $attributeEntity,
        LanguageEntity $languageEntity
    ) {
        $attributeValues = $objectEntity->getAttributeValues();

        foreach ($attributeValues as $attributeValue) {
            if (
                $attributeEntity->getId() == $attributeValue->getAttribute()->getId()
                && $attributeValue->getLanguage()->getId() === $languageEntity->getId()
            ) {
                return true;
            }
        }

        return false;
    }

    /**
     * @param ObjectEntity $objectEntity
     * @param AttributeEntity $attributeEntity
     * @param LanguageEntity $languageEntity
     * @param string $newValue
     */
    private function updateObjectValue(
        ObjectEntity $objectEntity,
        AttributeEntity $attributeEntity,
        LanguageEntity $languageEntity,
        $newValue
    ) {
        $attributeValues = $objectEntity->getAttributeValues();

        foreach ($attributeValues as $attributeValue) {
            if (
                $attributeEntity->getId() == $attributeValue->getAttribute()->getId()
                && $attributeValue->getLanguage()->getId() === $languageEntity->getId()
            ) {
                $attributeValue->setValue($newValue);
                $this->objectDbM->data()->objectAttributeValue()->save($attributeValue);
                $this->objectAttributeValue = $attributeValue;
            }
        }
    }

    /**
     * @param ObjectEntity $objectEntity
     * @param AttributeEntity $attributeEntity
     * @param LanguageEntity $languageEntity
     * @param string $objectValue
     */
    private function addObjectValue(
        ObjectEntity $objectEntity,
        AttributeEntity $attributeEntity,
        LanguageEntity $languageEntity,
        $objectValue
    ) {
        $this->objectAttributeValue = $this->objectDbM->entity()->objectAttributeValue();
        $this->objectAttributeValue
            ->setLanguage($languageEntity)
            ->setObject($objectEntity)
            ->setAttribute($attributeEntity)
            ->setValue($objectValue);

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

    /**
     * @return ObjectAttributeValue
     */
    public function getObjectAttributeValue()
    {
        return $this->objectAttributeValue;
    }

    /**
     * Validate entity
     *
     * @param object $entity
     * @return bool
     */
    protected function validate($entity)
    {
        $errors = $this->apiM->validator()->validate($entity);

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