<?php

/**
 * Class Delete
 *
 * 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\Delete;

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\Delete\AttributeGroup as ModelIn;
use Sso\Webservices\ObjectBundle\Database\Manager as DatabaseManager;

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

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

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

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

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

    /**
     * Returns a xml-string with allowed structure
     *
     * @return string
     */
    protected function _xmlAllowedElements()
    {
        return '<AttributeGroupType required="true">'
            . '<Id required="true"/>'
            . '<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\Delete\AttributeGroup', 'xml');
        $this->validate($modelIn);

        $this->attributeGroupModel = $this->objectDbM->data()->attributeGroup()->find($modelIn->getId());

        $this->deleteAttributeGroupEntity($modelIn);
    }

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

        if (!$this->attributeGroupModel->getAttributes()->isEmpty() && !$modelIn->isDeleteReferences()) {
            $this->apiM->errors()->addError(new ExternalError('agd002', 'Can not delete AttributeGroup',
                'AttributeGroup has referenced Attributes!', 'Please delete all referenced Attributes first.'));
            throw new InvalidRecordException('Delete AttributeGroup failed');
        }

        if (!$this->attributeGroupModel->getAttributes()->isEmpty() && $modelIn->isDeleteReferences()) {
            $this->deleteAttributesWithValues();
        }

        $attributeGroupModel = clone $this->attributeGroupModel;

        $this->objectDbM->data()->attributeGroup()->delete($this->attributeGroupModel);

        $this->attributeGroupModel = $attributeGroupModel;

    }

    private function deleteAttributesWithValues()
    {
        foreach ($this->attributeGroupModel->getAttributes() as $attribute) {

            if (!$attribute->getAttributeValues()->isEmpty()) {
                foreach ($attribute->getAttributeValues() as $objectValue) {
                    $this->objectDbM->data()->objectAttributeValue()->delete($objectValue);
                }
            }

            $this->objectDbM->data()->attribute()->delete($attribute);
        }
    }

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

}
