<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Addfunctions;

class PlzOperations
{
  public static function getPlzOhneOrt(?string $ort): string
  {
    $ort = $ort ?? '';
    $ary = explode(' ', $ort);

    $toolsettings = \ToolSettingsAPI::getToolSettings(4);
    $plzValidationSetting = $toolsettings->plzValidierung;

    switch ($plzValidationSetting) {
      case VALIDIERUNG_PLZ_KEINE:
        return trim($ary[0]);
      case VALIDIERUNG_PLZ_4:
        return preg_match('/^\\d{4}$/', $ary[0]) ? $ary[0] : '';
      case VALIDIERUNG_PLZ_5:
        return preg_match('/^\\d{5}$/', $ary[0]) ? $ary[0] : '';
      case VALIDIERUNG_PLZ_45:
      default:
        return preg_match('/^\\d{4,5}$/', $ary[0]) ? $ary[0] : '';
    }
  }

  public static function getOrtOhnePlz(?string $ort): string
  {
    $ort = $ort ?? '';
    if (!\StringOperations::containsDigit($ort)) {
      return $ort;
    }

    $ary = explode(' ', $ort);
    $return = $ary[1] ?? '';
    for ($i = 2; $i < count($ary); $i++) {
      $return .= ' ' . $ary[$i];
    }

    return $return;
  }

  
  public static function getOrtStrFromPlzOrt(string $nation, string $nurplz, string $nurort): string
  {
    if (!self::isPlzValidationInternational()) {
      return trim($nurplz) . ' ' . trim($nurort);
    }

    $separator = new \Kufer\Web\Classes\Plz\PlzOrtSeparator();
    $plzFirst = $separator->isPlzBeforeOrtByNation($nation);
    if (is_null($plzFirst)) {
      $result = trim($nurort);
    } elseif ($plzFirst) {
      $result = trim($nurplz) . ' ' . trim($nurort);
    } else {
      $result = trim($nurort) . ' ' . trim($nurplz);
    }

    return $result;
  }

  public static function getPlzFromPlzOrtStr(string $nation, string $ort): string
  {
    if (!self::isPlzValidationInternational()) {
      return self::getPlzOhneOrt($ort);
    }

    $separator = new \Kufer\Web\Classes\Plz\PlzOrtSeparator();
    try {
      $plzInfo = $separator->evaluatePlzOrtByNation($ort, $nation);
    } catch (\Exception $ex) {
      return '';
    }

    return $plzInfo->plz ?? self::getPlzOhneOrt($ort);
  }

  public static function getOrtFromPlzOrtStr(string $nation, string $ort): string
  {
    if (!self::isPlzValidationInternational()) {
      return self::getOrtOhnePlz($ort);
    }

    $separator = new \Kufer\Web\Classes\Plz\PlzOrtSeparator();
    try {
      $plzInfo = $separator->evaluatePlzOrtByNation($ort, $nation);
    } catch (\Exception $ex) {
      return self::getOrtOhnePlz($ort);
    }

    return $plzInfo->ort ?? self::getOrtOhnePlz($ort);
  }

  private static function isPlzValidationInternational(): bool
  {
    $toolsettings = \ToolSettingsAPI::getToolSettings(4);

    return $toolsettings->plzValidierung == VALIDIERUNG_PLZ_INTERNATIONAL;
  }
}