<?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\Attribute as ModelAttribute;
use Sso\WebserviceBundle\Entity\Webservice\Type\Application as ModelApplication;
use Doctrine\ORM\EntityRepository;

/**
 * Class Attribute
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\WebserviceBundle\Database\Webservice
 */
class Attribute extends Base
{

    /**
     * Save attribute to database
     * @param ModelAttribute $typeAttribute
     * @return bool Returns true on success, false on validation failure
     */
    public function saveAttribute(ModelAttribute $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;
    }

    /**
     * Save list of attributes
     * @param array $attributes
     * @return boolean
     */
    public function saveAttributes(array $attributes)
    {
        // Do default validation
        $isValid = true;
        foreach ($attributes as $entity) {
            $entity->setValidator($this->validator);
            if (!$entity->isValid()) {
                $isValid = false;
            }
        }
        if (!$isValid) {
            return false;
        }

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

        foreach ($attributes as $entity) {
            $this->entityManager->persist($entity);
        }
        $this->entityManager->flush();

        return true;
    }

    /**
     * Delete attribute
     * @param ModelAttribute $typeAttribute
     * @return bool True on success
     */
    public function deleteAttribute(ModelAttribute $typeAttribute)
    {
        $typeAttribute->setValidator($this->validator);
        if (!$typeAttribute->validate(array('ApplicationAttribute_Delete'))) {
            return false;
        }

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

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

        return true;
    }

    /**
     * Get attribute by id
     * @param string $attributeId
     * @return ModelAttribute
     */
    public function getAttributeById($attributeId)
    {
        return $this->entityManager->getRepository('Sso\WebserviceBundle\Entity\Webservice\Type\Attribute')->findOneBy(array('Id' => $attributeId));
    }

    /**
     * Get attribute by name
     * @param ModelApplication $application
     * @param string $attributeName
     * @return ModelAttribute|null
     */
    public function getAttributeByName(ModelApplication $application, $attributeName)
    {
        $attributeName = strtolower($attributeName);
        foreach ($application->getAttributes() as $attribute) {
            if ($attribute->getLowername() == $attributeName) {
                return $attribute;
            }
        }
        return null;
    }

    /**
     * Find a list of attributes by attribute-name
     * @param $attributeName
     * @param int $limit
     * @param int $offset
     * @return ModelAttribute[]
     */
    public function getAttributesByName($attributeName, $limit = 1, $offset = 0)
    {
        $attributeName = str_replace('%', '\%', strtolower($attributeName));
        return $this->getAttributeRepository()
            ->createQueryBuilder('a')
            ->where('a.Lowername LIKE :attributeName')
            ->setParameter('attributeName', $attributeName . '%')
            ->orderBy('a.Lowername')
            ->setMaxResults($limit)
            ->setFirstResult($offset)
            ->getQuery()
            ->getResult();
    }

    /**
     * Find a list of attributes by attribute-name
     * @param string $attributeName
     * @param ModelApplication $application
     * @param int $limit
     * @param int $offset
     * @return \Sso\WebserviceBundle\Entity\Webservice\Type\Attribute[]
     */
    public function getAttributesByNameAndApplication($attributeName, ModelApplication $application, $limit = 1, $offset = 0)
    {
        $attributeName = str_replace('%', '\%', strtolower($attributeName));
        return $this->getAttributeRepository()
            ->createQueryBuilder('a')
            ->where('a.Application=:application')
            ->andWhere('a.Lowername LIKE :attributeName')
            ->setParameter('application', $application)
            ->setParameter('attributeName', $attributeName . '%')
            ->orderBy('a.Lowername')
            ->setMaxResults($limit)
            ->setFirstResult($offset)
            ->getQuery()
            ->getResult();
    }

    /**
     * Get attribute by name
     * @param ModelApplication $application
     * @param ModelAttribute $attributeValue
     * @return ModelAttribute|null
     */
    public function getAttributeByAttributeValue(ModelApplication $application, ModelAttribute $attributeValue)
    {
        $attributeName = strtolower($attributeValue->getName());
        foreach ($application->getAttributes() as $attribute) {
            if ($attribute->getLowername() == $attributeName) {
                return $attribute;
            }
        }
        return null;
    }

    /**
     * @return EntityRepository
     */
    public function getAttributeRepository()
    {
        return $this->entityManager->getRepository('Sso\WebserviceBundle\Entity\Webservice\Type\Attribute');
    }
}
