<?php

namespace idoit\Component\Table\Filter\Operation;

use idoit\Component\Property\Property;
use isys_application;
use isys_cmdb_dao_list_objects;
use isys_notify;

/**
 *
 *
 * @package     i-doit
 * @subpackage
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */
class DateTimeOperation extends PropertyOperation
{
    /**
     * @param string $filter
     * @param string $value
     *
     * @return bool
     */
    public function isApplicable($filter, $value)
    {
        $property = $this->getProperty($filter);

        return $property[Property::C__PROPERTY__DATA][Property::C__PROPERTY__DATA__TYPE] === C__TYPE__DATE_TIME;
    }

    /**
     * Apply Property
     *
     * @param isys_cmdb_dao_list_objects $listDao
     * @param array|Property             $property
     * @param string                     $name
     * @param string                     $value
     *
     * @return mixed
     */
    protected function applyProperty(isys_cmdb_dao_list_objects $listDao, $property, $name, $value)
    {
        $timestamp = strtotime($value);

        if ($timestamp !== false) {
            $fieldName = $listDao->get_database_component()->escapeColumnName($name);

            // @see ID-9261 If the user passes no specific time, use the 'date' converter.
            if (date('H:i:s', $timestamp) === '00:00:00') {
                $formattedDate = $listDao->convert_sql_date($timestamp);
                $listDao->add_additional_having_conditions("CAST({$fieldName} AS Date) LIKE {$formattedDate}");
            } else {
                $formattedDate = $listDao->convert_sql_datetime($timestamp);
                $listDao->add_additional_having_conditions("{$fieldName} LIKE {$formattedDate}");
            }

            return true;
        } else {
            isys_notify::warning(isys_application::instance()->container->get('language')->get('LC_CALENDAR_POPUP__WRONGDATE'));
        }

        return false;
    }
}
