<?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\Object\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\Object as EntityObject;
use Sso\Webservices\ObjectBundle\Model\Request\Object\Delete\Entity as RequestModel;
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\Object\Delete
 */
class Delete
{

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

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

    /**
     *
     * @var EntityObject
     */
    protected $objectEntity;

    /**
     * @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 '<ObjectType required="true">'
            . '<Guid />'
            . '<ReferenceId />'
            . '</ObjectType>';
    }

    /**
     * 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->ObjectType->saveXML(),
            'Sso\Webservices\ObjectBundle\Model\Request\Object\Delete\Entity', 'xml');
        $this->validateEntity();

        $this->objectEntity = $this->findObjectEntity($this->helperModel);

        $this->deleteObject();
    }

    /**
     * Find object entity by guid or by referenceId
     *
     * @param RequestModel $requestModel
     * @return EntityObject
     */
    private function findObjectEntity($requestModel)
    {
        if (empty($requestModel->getGuid()) && empty($requestModel->getReferenceId())) {
            $this->apiM->errors()->addError(new ExternalError('o001', 'Object not found', 'No identifier given.',
                'Please specify guid or referenceId.'));
            throw new InvalidRecordException('Missing identifier');
        }

        $objectEntity = null;

        if (!empty($requestModel->getGuid())) {
            $search = ['guid' => $requestModel->getGuid()];
            $objectEntity = $this->objectDbM->data()->object()->findBy($search);
        }

        if (!empty($requestModel->getReferenceId())) {
            $search = ['referenceId' => $requestModel->getReferenceId()];
            $objectEntity = $this->objectDbM->data()->object()->findBy($search);
        }

        return count($objectEntity) > 0 ? $objectEntity[0] : $objectEntity;
    }

    public function deleteObject()
    {
        if (!$this->objectEntity) {
            $this->apiM->errors()->addError(new ExternalError('o001', 'Object not found', 'Object not found',
                'Object not found'));
            throw new InvalidRecordException('Object not found');
        }

        $entityClone = clone $this->objectEntity;
        $this->objectDbM->data()->object()->delete($this->objectEntity);

        $this->objectEntity = $entityClone;
    }

    /**
     * @return EntityObject
     */
    public function getObjectModel()
    {
        return $this->objectEntity;
    }

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