<?php

/**
 * Request Type 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\Type\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\Type as EntityType;

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

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


    /**
     *
     * @var \Sso\Webservices\ObjectBundle\Model\Request\Type\Delete\Entity
     */
    protected $helperModel;

    /**
     *
     * @var EntityType
     */
    protected $typeORM;

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

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

    /**
     * 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->TypeType->saveXML(),
            'Sso\Webservices\ObjectBundle\Model\Request\Type\Delete\Entity', 'xml');
        $this->validate($requestModel);

        $this->typeORM = $this->apiM->database()->webservice()->types()->getTypeRepository()->find($requestModel->getId());

        $this->deleteTypeEntity();
    }

    public function deleteTypeEntity()
    {
        if (!$this->typeORM) {
            $this->apiM->errors()->addError(new ExternalError('t001', 'Type not found', 'Type not found',
                'Type not found'));
            throw new InvalidRecordException('Type not found');
        }

        if (count($this->typeORM->getObjects()) > 0) {
            $this->apiM->errors()->addError(new ExternalError('t002', 'This Type is connected by other objects',
                'This Type is connected by other objects',
                'This Type is connected by other objects! Please delete the corresponding objects first!'));
            throw new InvalidRecordException('This Type is connected by other objects! Please delete the corresponding objects first!');
        }

        if (count($this->typeORM->getAttributeGroups()) > 0) {
            $this->apiM->errors()->addError(new ExternalError('t003',
                'This Type is connected by other attribute groups', 'This Type is connected by other attribute groups',
                'This Type is connected by other objects! Please delete the corresponding attribute groups first!'));
            throw new InvalidRecordException('This Type is connected by other attribute groups! Please delete the corresponding attribute groups first!');
        }

        $entityClone = clone $this->typeORM;

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

        $this->typeORM = $entityClone;
    }

    /**
     *
     * @return EntityType
     */
    public function getTypeModel()
    {
        return $this->typeORM;
    }

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

}
