<?php

namespace idoit\Module\Forms\Model\Validators\Category;

use idoit\Module\Forms\Model\Validators\GenericValidator;
use idoit\Module\Forms\Model\Validators\ValidatorInterface;
use isys_application;
use isys_cmdb_dao_category;

class CustomFieldsValidator extends AbstractCategoryValidator implements ValidatorInterface
{
  public const CATEGORY_CONST = 'C__CATG__CUSTOM_FIELDS';

  /**
   * @param string $categoryConst
   *
   * @return bool
   */
  public function isApplicable(string $categoryConst): bool
  {
    return strpos($categoryConst, self::CATEGORY_CONST) !== false;
  }

  /**
   * @param array                  $formData
   * @param isys_cmdb_dao_category $categoryDao
   *
   * @return array|null
   */
  public function validate(array $formData, isys_cmdb_dao_category $categoryDao): ?array
  {
    $genericValidator = (GenericValidator::factory());
    $language = isys_application::instance()->container->get('language');
    $issues = [];
    $properties = $categoryDao->get_properties(C__PROPERTY__WITH__VALIDATION);

    if (is_array($formData)) {
      foreach ($formData as $key => $value) {
        if (!isset($properties[$key]) && !isset($properties[$key][C__PROPERTY__CHECK])) {
          continue;
        }
        if (!empty($value) && $properties[$key][C__PROPERTY__UI][C__PROPERTY__UI__TYPE] == C__PROPERTY__UI__TYPE__NUMERIC && !is_numeric($value)) {
          $issues[$key] = $language->get('LC__SETTINGS__CMDB__VALIDATION_MESSAGE__NEEDS_TO_BE_FLOAT');
        }
      }
    }

    $parentValidationResult = $genericValidator->validate($formData, $categoryDao);

    if(is_array($parentValidationResult)) {
      $issues = array_merge($issues, $parentValidationResult);
    }

    return !empty($issues) ? $issues : null;
  }
}
