<?php

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

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

class NetDhcpValidator extends AbstractCategoryValidator implements ValidatorInterface
{
  public const CATEGORY_CONST = 'C__CATS__NET_DHCP';

  /**
   * @param array                  $formData
   * @param isys_cmdb_dao_category $categoryDao
   *
   * @return array|null
   * @throws \Exception
   */
  public function validate(array $formData, isys_cmdb_dao_category $categoryDao): ?array
  {
    $genericValidator = (GenericValidator::factory());
    $language = isys_application::instance()->container->get('language');

    $errorMessage = $language->get('LC__CMDB__CATS__NET_IP_ADDRESSES__IP_INVALID');
    $issues = [];
    $ipValidation = [
      'ipv4' => [],
      'ipv6' => [],
    ];

    if (isset($formData['range_from']) && isset($formData['range_to'])) {
      if (!Ip::validate_ip($formData['range_from'])) {
        $ipValidation['ipv4']['range_from'] = $errorMessage;
      }

      if (!Ip::validate_ip($formData['range_to'])) {
        $ipValidation['ipv4']['range_to'] = $errorMessage;
      }

      if (!Ip::validate_ipv6($formData['range_from'])) {
        $ipValidation['ipv6']['range_from'] = $errorMessage;
      }

      if (!Ip::validate_ipv6($formData['range_to'])) {
        $ipValidation['ipv6']['range_to'] = $errorMessage;
      }

      if (!empty($ipValidation['ipv4']) && !empty($ipValidation['ipv6'])) {
        $issues = count($ipValidation['ipv4']) > count($ipValidation['ipv6']) ?
          $ipValidation['ipv6']: $ipValidation['ipv4'];
      }
    }

    unset($formData['range_from'], $formData['range_to']);

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

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

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