<?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\ObjectValue\Show;

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\ObjectAttributeValue as EntityObjectValue;
use Sso\Webservices\ObjectBundle\Model\Request\ObjectValue\Show\Entity as ModelIn;

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

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


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

    /**
     * @var EntityObjectValue[]
     */
    protected $objectValueModels;


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

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

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

        $this->getObjectValueEntities();
    }

    protected function getObjectValueEntities()
    {
        $repo = $this->apiM->database()->webservice()->objectValues()->getObjectValuesRepository();

        // data
        $id = $this->helperModel->getId();

        if ($id) {
            $search = ["id" => $id];
            $this->objectValueModels = $repo->findBy($search);
            return;
        }

        $this->objectValueModels = $repo->findAll();
    }

    /**
     * @return int
     */
    public function getObjectsValueCount()
    {
        $repo = $this->apiM->database()->webservice()->objectValues()->getObjectValuesRepository();

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

    /**
     *
     * @return EntityObjectValue[]
     */
    public function getObjectValueModels()
    {
        return $this->objectValueModels;
    }

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

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

}
