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

namespace Sso\Webservices\ObjectBundle\Model\Request\AttributeGroup\Update;

use Guzzle\Service\Resource\Model;
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\AttributeGroup as EntityAttributeGroup;
use Sso\Webservices\ObjectBundle\Model\Request\AttributeGroup\Update\AttributeGroup as ModelIn;

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

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

    /**
     * @var EntityAttributeGroup
     */
    protected $attributeGroupModel;

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

    /**
     * Returns a xml-string with allowed structure
     *
     * @return string
     */
    protected function _xmlAllowedElements()
    {
        return '<AttributeGroupType required="true">'
            . '<Id required="true"/>'
            . '<Name/>'
            . '<AddTypes>'
            . '<TypeId multiple="true"/>'
            . '</AddTypes>'
            . '<DeleteTypes>'
            . '<TypeId multiple="true"/>'
            . '</DeleteTypes>'
            . '<DeleteReferences/>'
            . '</AttributeGroupType>';
    }

    /**
     * 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->AttributeGroupType->saveXML(),
            'Sso\Webservices\ObjectBundle\Model\Request\AttributeGroup\Update\AttributeGroup', 'xml');
        $this->validate($modelIn);

        $this->attributeGroupModel = $this->apiM->database()->webservice()->attributeGroup()->getAttributeGroupById($modelIn->getId());

        $this->updateAttributeGroupEntity($modelIn);
    }

    /**
     * @param ModelIn $modelIn
     */
    public function updateAttributeGroupEntity(ModelIn $modelIn)
    {
        if (!$this->attributeGroupModel) {
            $this->apiM->errors()->addError(new ExternalError('ag001', 'attributeGroup not found',
                'attributeGroup not found', 'attributeGroup not found'));
            throw new InvalidRecordException('AttributeGroup not found');
        }

        $this->addTypes($modelIn);
        $this->deleteTypes($modelIn);

        if ($modelIn->getName() != null) {
            $this->attributeGroupModel->setName($modelIn->getName());
        }

        $this->apiM->database()->webservice()->attributeGroup()->saveAttributeGroup($this->attributeGroupModel);
    }

    /**
     * @param ModelIn $modelIn
     */
    private function addTypes(ModelIn $modelIn)
    {
        if (count($modelIn->getAddTypes()) > 0) {
            foreach ($modelIn->getAddTypes() as $addType) {
                $addTypeEntity = $this->apiM->database()->webservice()->types()->find($addType->getTypeId());
                if (!$addTypeEntity) {
                    $this->apiM->errors()->addError(new ExternalError('v001', 'type id not found', 'type id not found',
                        'type id ' . $addTypeEntity->getId() . ' not found'));
                    throw new InvalidRecordException('Type not found');
                }
                $this->attributeGroupModel->addType($addTypeEntity);
            }
        }
    }

    /**
     * @param ModelIn $modelIn
     */
    private function deleteTypes(ModelIn $modelIn)
    {
        if (count($modelIn->getDeleteTypes()) > 0) {
            foreach ($modelIn->getDeleteTypes() as $deleteType) {
                $deleteTypeEntity = $this->apiM->database()->webservice()->types()->find($deleteType->getTypeId());
                if (!$deleteTypeEntity) {
                    $this->apiM->errors()->addError(new ExternalError('v001', 'type id not found', 'type id not found',
                        'type id ' . $deleteTypeEntity->getId() . ' not found'));
                    throw new InvalidRecordException('Type not found');
                }

                // Check for referenced attribute values.
                foreach ($this->attributeGroupModel->getTypes() as $entityType) {
                    if ($entityType->getId() == $deleteTypeEntity->getId()) {

                        foreach ($entityType->getObjects() as $entityObject) {
                            foreach ($entityObject->getAttributeValues() as $entityAttributeValue) {

                                if ($this->attributeGroupModel->getId() == $entityAttributeValue->getAttribute()->getAttributeGroup()->getId()) {

                                    if (!$modelIn->isDeleteReferences()) {
                                        $this->apiM->errors()->addError(new ExternalError('ag001',
                                            'Can not delete type',
                                            'There are objects with attribute values for this type/attributeGroup!',
                                            'Please delete all referenced AttributeValues first.'));
                                        throw new InvalidRecordException('Delete Type failed');
                                    }

                                    // @TODO: removing attribute values not working!
                                    $entityObject->removeAttributeValue($entityAttributeValue);
                                    $this->apiM->database()->webservice()->attributeGroup()->saveAttributeGroup($this->attributeGroupModel);
                                }

                            }
                        }

                    }
                }

                $this->attributeGroupModel->removeType($deleteTypeEntity);
            }
        }
    }

    /**
     *
     * @return EntityAttributeGroup
     */
    public function getAttributeGroupModel()
    {
        return $this->attributeGroupModel;
    }

    /**
     * Validate entity
     *
     * @param ModelIn $entity
     * @param array $validationGroups
     * @return bool
     */
    protected function validate(ModelIn $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;
    }

    /**
     * @return int
     */
    public function getAttributeGroupsCount()
    {
        $repo = $this->apiM->database()->webservice()->attributeGroup()->getAttributeGroupRepository();

        return $repo->createQueryBuilder('b')
            ->select('count(b.id)')
            ->getQuery()
            ->getSingleScalarResult();
    }
}
