<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Anmeldung\OnlinePortal;

class AnmeldeOnlinePortalDataSingleton
{
  
  private $belegIdUndStornoHash = array();

  private $webPlattformStatusUndInfos = array();

  private function __construct()
  {
    
  }

  public static function instance(): AnmeldeOnlinePortalDataSingleton
  {
    static $instance = null;
    if (is_null($instance)) {
      $instance = new AnmeldeOnlinePortalDataSingleton();
    }

    return $instance;
  }

  private function makeKey(string $knr, int $tnr): string
  {
    return $tnr . '_' . trim($knr);
  }

  
  public function addStornoLinkData(string $knr, int $tnr, string $name, string $vorname, string $email, int $belegId, string $stornohash): void
  {
    if ($tnr >= 0 && trim($knr) != '' && $belegId > 0 && trim($stornohash) != '') {
      $this->belegIdUndStornoHash[$this->makeKey($knr, $tnr)] = new \Tuple(new StornoLink($belegId, $stornohash), $knr, $name, $vorname, $email);
    }
  }

  
  public function getStornoLinkDataByTnr(string $knr, int $tnr): ?StornoLink
  {
    if (isset($this->belegIdUndStornoHash[$this->makeKey($knr, $tnr)])) {
      return $this->belegIdUndStornoHash[$this->makeKey($knr, $tnr)]->getFirst();
    }

    return null;
  }

  public function getStornoLinkDataByTnInfos(string $knr, string $name, string $vorname, string $email): ?StornoLink
  {
    $eintraege = array_filter($this->belegIdUndStornoHash, function($tuple) use ($knr, $name, $vorname, $email) {
      return $tuple->getSecond() == $knr
             && $tuple->getThird() == $name
             && $tuple->getFourth() == $vorname
             && $tuple->getFifth() == $email;
    });

    if (count($eintraege) == 1) { 
      return \ArrayOperations::firstValue($eintraege)->getFirst();
    } else { 
      return null;
    }
  }

  
  public function addWebportalData(string $knr, int $tnr, string $name, string $vorname, string $email, int $status, array $webPlattformInfos): void
  {
    if ($tnr >= 0 && trim($knr) != '' && $status >= 0) { 
      $this->webPlattformStatusUndInfos[$this->makeKey($knr, $tnr)] = new \Tuple($status, $webPlattformInfos, $knr, $name, $vorname, $email);
    }
  }

  
  public function getWebportalDataByTnr(string $knr, int $tnr): ?\Tuple
  {
    return $this->webPlattformStatusUndInfos[$this->makeKey($knr, $tnr)] ?? null;
  }

  public function getWebportalDataByTnInfos(string $knr, string $name, string $vorname, string $email): ?\Tuple
  {
    $eintraege = array_filter($this->webPlattformStatusUndInfos, function($tuple) use ($knr, $name, $vorname, $email) {
      return $tuple->getThird() == $knr
        && $tuple->getFourth() == $name
        && $tuple->getFifth() == $vorname
        && $tuple->getSixth() == $email;
    });

    if (count($eintraege) == 1) { 
      return \ArrayOperations::firstValue($eintraege);
    } else { 
      return null;
    }
  }
}