<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private 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  2018 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\WebserviceBundle\Database\Webservice;

use Sso\WebserviceBundle\Entity\Webservice\Type;

/**
 * Class AttributeValue
 * @package Sso\WebserviceBundle\Database\Webservice
 */
class AttributeValue extends Base
{
    /**
     * Save attribute value to database
     * @param Type\AttributeValue $typeAttribute
     * @return bool Returns true on success, false on validation failure
     */
    public function saveAttributeValue(Type\AttributeValue $typeAttribute)
    {
        // Do default validation
        $typeAttribute->setValidator($this->validator);
        if (!$typeAttribute->isValid()) {
            return false;
        }

        if ($this->readonly) {
            return false;
        }

        $this->entityManager->persist($typeAttribute);
        $this->entityManager->flush($typeAttribute);

        return true;
    }

    /**
     * Delete attribute values
     * @param \Sso\WebserviceBundle\Entity\Webservice\Type\User $user
     * @param \Sso\WebserviceBundle\Entity\Webservice\Type\Application $application
     * @throws \Sso\WebserviceBundle\Database\Webservice\Exception
     */
    public function deleteAttributeValues(Type\User $user, Type\Application $application)
    {
        if ($this->readonly) {
            return false;
        }

        $dql = 'DELETE FROM Sso\WebserviceBundle\Entity\Webservice\Type\AttributeValue av '
                . 'WHERE av.UserId=:UserId '
                . 'AND av.ApplicationId=:ApplicationId';
        $query = $this->entityManager->createQuery($dql);
        $query->setParameters(array(
            'UserId' => $user->getId(),
            'ApplicationId' => $application->getId(),
        ));
        $query->execute();
    }

    /**
     * Save a collection of attribute values
     * @param array $attributeValues
     */
    public function saveAttributeValueCollection(array $attributeValues)
    {
        if ($this->readonly) {
            return false;
        }

        foreach ($attributeValues as $attributeValue) {

            // Get index on multi type
            if ($attributeValue->getAttribute()->isArray()) {
                $attributeValue->setIndex($this->getIndex($attributeValue));
            }

            $this->saveAttributeValue($attributeValue);
        }
    }

    /**
     * Delete attribute values
     * @param \Sso\WebserviceBundle\Entity\Webservice\Type\User $user
     * @param array $attributeValues
     * @return bool
     * @throws \Sso\WebserviceBundle\Database\Webservice\Exception
     */
    public function deleteAttributeValueCollection(Type\User $user, array $attributeValues)
    {
        if ($this->readonly) {
            return false;
        }

        $attributeIds = array();
        foreach ($attributeValues as $attributeValue) {
            $attributeIds[$attributeValue->getAttribute()->getId()] = $attributeValue->getAttribute()->getId();
        }
        $dql = 'DELETE FROM Sso\WebserviceBundle\Entity\Webservice\Type\AttributeValue av '
                . 'WHERE av.UserId=:UserId '
                . 'AND av.AttributeId IN (:AttributeId)';
        $query = $this->entityManager->createQuery($dql);
        $query->setParameters(array(
            'UserId' => $user->getId(),
            'AttributeId' => $attributeIds,
        ));
        $query->execute();
    }

    /**
     * Get next index for multi values
     * 
     * @param \Sso\WebserviceBundle\Entity\Webservice\Type\AttributeValue $attributeValue
     */
    public function getIndex(Type\AttributeValue $attributeValue)
    {
        $criteria = array(
            'ApplicationId' => $attributeValue->getApplication()->getId(),
            'UserId' => $attributeValue->getUser()->getId(),
            'AttributeId' => $attributeValue->getAttribute()->getId(),
        );
        $orderBy = array(
            'Index' => 'DESC',
        );
        $attributeValue = $this->entityManager->getRepository('Sso\WebserviceBundle\Entity\Webservice\Type\AttributeValue')->findOneBy($criteria, $orderBy);
        return $attributeValue ? $attributeValue->getIndex() + 1 : 0;
    }
}
