<?php
namespace idoit\Module\Cmdb\Component\SyncMerger\DataRetriever;

use idoit\Component\Property\Property;
use isys_cmdb_dao_category;
use isys_request;

class ByReference implements DataRetrieverInterface
{
    /**
     * @param Property $property
     *
     * @return bool
     */
    public static function isApplicable(Property $property)
    {
        $references = $property->getData()
            ->getReferences();

        if (is_array($references) && isset($references[1])) {
            return true;
        }
        return false;
    }

    /**
     * @param Property          $property
     * @param array             $properties
     * @param array             $categoryData
     * @param array             $currentData
     * @param isys_request|null $request
     *
     * @return mixed|null
     */
    public function retrieveValue(Property $property, array $properties, array $categoryData, array $currentData, isys_cmdb_dao_category $dao, isys_request $request = null)
    {
        $categoryTable = $dao->get_table();
        $references = $property->getData()->getReferences();

        if (is_array($references)) {
            if (isset($categoryData[$references[1]])) {
                return $categoryData[$references[1]];
            }

            // @see ID-10890 This can happen if the table was not joined.
            if (isset($categoryData[$categoryTable . '__' . $references[1]])) {
                return $categoryData[$categoryTable . '__' . $references[1]];
            }
        }

        return null;
    }
}
