<?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 NetValidator extends AbstractCategoryValidator implements ValidatorInterface
{
  public const CATEGORY_CONST = 'C__CATS__NET';

  public function validate(array $formData, isys_cmdb_dao_category $categoryDao): ?array
  {
    $genericValidator = (GenericValidator::factory());
    $language = isys_application::instance()->container->get('language');
    $issues = [];

    switch ($formData['type']) {
      case defined_or_default('C__CATS_NET_TYPE__IPV6'):
        if (isset($formData['address_v6'])) {
          $formData['address'] = $formData['address_v6'];
        }

        if (filter_var($formData['address'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
          $issues['address'] = $language->get('LC__UNIVERSAL__FIELD_VALUE_IS_INVALID');
        }
        break;
      case defined_or_default('C__CATS_NET_TYPE__IPV4'):
      default:
      if (filter_var($formData['address'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
        $issues['address'] = $language->get('LC__UNIVERSAL__FIELD_VALUE_IS_INVALID');
      }

      if (filter_var($formData['netmask'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
        $issues['netmask'] = $language->get('LC__UNIVERSAL__FIELD_VALUE_IS_INVALID');
      }
        break;
    }

    unset($formData['address'], $formData['address_v6'], $formData['netmask']);

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

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

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