<?php
/**
 * i-doit - Documentation and CMDB solution for IT environments
 *
 * This file is part of the i-doit framework. Modify at your own risk.
 *
 * Please visit http://www.i-doit.com/license for a full copyright and license information.
 *
 * @version     1.10
 * @package     i-doit
 * @author      synetics GmbH
 * @copyright   synetics GmbH
 * @url         http://www.i-doit.com
 * @license     http://www.i-doit.com/license
 */
/**
 *
 *
 * @package     i-doit
 * @subpackage
 * @author      Pavel Abduramanov <pabduramanov@i-doit.com>
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */

namespace idoit\Component\Table\Filter\Condition;

use idoit\Module\Cmdb\Model\Ci\Table\Config;
use idoit\Module\Cmdb\Model\Ci\Table\Property;

/**
 * Finds the type of column in table configuration and checks the inner condition with the column type
 *
 * @package idoit\Component\Table\Filter\Condition
 */
class TypeCondition implements ConditionInterface
{
    /**
     * @var ConditionInterface
     */
    private $innerCondition;

    /**
     * @var Config
     */
    private $tableConfig;

    /**
     * Gets the name of property to proof
     *
     * @param Property $property
     *
     * @return string
     */
    private function getPropertyName(Property $property)
    {
        $name = $property->getClass() . '__' . $property->getKey();
        if ($property->getCustomCatID() > 0 && $property->getKey() == 'description')
        {
            $name .= '_' . $property->getCustomCatID();
        }

        return $name;
    }

    /**
     * TypeCondition constructor.
     *
     * @param Config             $tableConfig    - table config to get the information about types
     * @param ConditionInterface $innerCondition - inner condition to check
     */
    public function __construct(Config $tableConfig, ConditionInterface $innerCondition)
    {
        $this->innerCondition = $innerCondition;
        $this->tableConfig    = $tableConfig;
    }

    /**
     * @param string $name
     *
     * @return bool
     */
    public function check($name)
    {
        foreach ($this->tableConfig->getProperties() as $i => $property)
        {
            if ($this->getPropertyName($property) === $name)
            {
                return $this->innerCondition->check($property->getType());
            }
        }

        return false;
    }
}
