<?php

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

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

use Sso\Webservices\ObjectBundle\Model\Response\AttributeGroup\Show\Entity\Attribute;
use Sso\Webservices\ObjectBundle\Model\Response\AttributeGroup\Show\Entity\AttributeGroup;
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\Show\Entity\AttributeGroup as ModelIn;
use Sso\Webservices\ObjectBundle\Database\Manager as DatabaseManager;

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

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

    /**
     *
     * @var EntityAttributeGroup[]
     */
    protected $attributeGroupModels;

    /**
     * @var ModelIn
     */
    protected $modelIn;

    /**
     * @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 multiple="true"/>'
            . '<Offset/>'
            . '<Limit/>'
            . '</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.');
        }

        $this->modelIn = $this->apiM->serializer()->deserialize($simpleXML->AttributeGroupType->saveXML(),
            'Sso\Webservices\ObjectBundle\Model\Request\AttributeGroup\Show\Entity\AttributeGroup', 'xml');
        $this->validate($this->modelIn);

        $this->getAttributeGroupEntities();
    }

    public function getAttributeGroupEntities()
    {
        $repo = $this->objectDbM->data()->attributeGroup();

        $attributeGroupId = $this->modelIn->getId();
        $offset = $this->modelIn->getOffset();
        $limit = $this->modelIn->getLimit();

        if ($attributeGroupId) {
            $search = ['id' => $attributeGroupId];
            $this->attributeGroupModels = $repo->findBy($search);
            return;
        }

        $defaultCriteria = [];
        if ($offset !== null || $limit !== null) {
            $this->attributeGroupModels = $repo->findBy($defaultCriteria, array(), $limit, $offset);
        } else {
            $this->attributeGroupModels = $repo->findBy($defaultCriteria);
        }
    }

    /**
     *
     * @return EntityAttributeGroup[]
     */
    public function getAttributeGroupModels()
    {
        return $this->attributeGroupModels;
    }

    /**
     * @return int
     */
    public function getAttributeGroupsCount()
    {
        return $this->objectDbM->data()->attributeGroup()->getCount();
    }

    /**
     * @return ModelIn
     */
    public function getRequestModel()
    {
        return $this->modelIn;
    }

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

}
