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

namespace Kufer\KuferTools\Oeffentlich\LoginAnfordern\Utils;

use Kufer\Web\Classes\Addfunctions\Guid;

abstract class NeuesLoginAnlegen
{
  public const NEUESLOGIN_SUCCESS = 1;
  public const NEUESLOGIN_ERROR_ALLGEMEIN = 2;
  public const NEUESLOGIN_ERROR_LOGIN_BEREITS_VORHANDEN = 3;
  public const NEUESLOGIN_ERROR_OPTIN_NICHT_GEFUNDEN = 4; 

  public function neuesLoginPerDmzAnlegen($pLogin, $pGeschlecht, $pName, $pVorname, $pPasswortHash, $pHashversion, $pEmail, $pDseUnterschriebenDatum, $auth_extern = 0)
  {
    $login = \StringOperations::strtoupper($pLogin);

    if ($this->loginBereitsVergeben($login)) {
      return self::NEUESLOGIN_ERROR_LOGIN_BEREITS_VORHANDEN;
    }

    $person = $this->getPersonObj($pGeschlecht, $pName, $pVorname, $pEmail, $pDseUnterschriebenDatum);
    $webUser = $this->createWebUser($login);

    $message = $this->getXml4Dmz($person, $webUser);

    try {
      $abgleichAPI = new \AbgleichAPI();
      $dmzResult = $abgleichAPI->sendeNachricht(
        $this->getDmzFeature(),
        new \Nutzlast($message)
      );
      if ($dmzResult->code != \AbgleichApiResult::CODE_SUCCESS) {
        return self::NEUESLOGIN_ERROR_ALLGEMEIN;
      }
      $content = \JsonOperations::getFromString($dmzResult->reason);
      $guid = new Guid($content->Guid);
      $wuGuid = new Guid($content->WebuserGuid);

      $person->guid = $guid;
      $personFromDb = $this->getPersonFromDb($person->guid);
      if ($personFromDb->isEmpty()) {
        $personFromDb = $this->insertPerson($person);
        if (is_null($personFromDb) || $personFromDb->getIdentifier()->isEmpty(false)) {
          return self::NEUESLOGIN_ERROR_ALLGEMEIN;
        }
      }
      $webUser->guid = $wuGuid;
      $webUser = $this->setWebuserFields($webUser, $guid, $personFromDb->id);
      $this->insertWebUser($webUser);
      $this->insertWebToolsUsers($webUser->getIdentifier());
      $this->insertPasswort($webUser, $pPasswortHash, $pHashversion, $auth_extern);

      return self::NEUESLOGIN_SUCCESS;
    } catch (\AbgleichApiException $aae) {
      \Logger::logg('Neues Login anlegen per DMZ - folgende Exception ist aufgetreten: ' . $aae->getMessage() . "\n" . ' [' . $aae->getTraceAsString() . ']', 200);

      return self::NEUESLOGIN_ERROR_ALLGEMEIN;
    }
  }

  
  abstract protected function getDmzFeature();

  abstract protected function getXml4Dmz($dozent, $webUser);

  abstract protected function getPersonObj($pGeschlecht, $pName, $pVorname, $pEmail, $pDseUnterschriebenDatum);

  abstract protected function getPersonFromDb($guid);

  abstract protected function getTyp();

  abstract protected function getwebToolsStdTempl();

  abstract protected function insertPerson($person);

  abstract protected function setWebuserFields($webUser, $personGuid, $personNr);

  private function loginBereitsVergeben($pLogin)
  {
    $dbwWebUser = new \DBWorkUser(1, true);
    $webUser = $dbwWebUser->getUserbyLogin($pLogin);

    return !$webUser->isEmpty() && !$webUser->getIdentifier()->isEmpty(false);
  }

  private function createWebUser($login)
  {
    $webUser = new \Benutzer();
    $webUser->dnr = -1;
    $webUser->login = $login;
    $webUser->admin = -1;
    $webUser->tnr = -1;
    $webUser->anr = -1;
    $webUser->ben = -1;

    return $webUser;
  }

  private function insertWebUser($webUser)
  {
    $dbwWebUser = new \DBWorkUser(1, true);
    $webUser->id = $dbwWebUser->insertUser($webUser, true);

    return $webUser;
  }

  
  private function insertWebToolsUsers($userIdentifier)
  {
    $dbwWebToolsUsers = new \DBWorkWebToolsUsers(1, true);
    $webToolsStdTempl = $this->getwebToolsStdTempl();
    $wtus = array();
    foreach ($webToolsStdTempl as $wtst) {
      $wtu = $this->getWebToolsUsers4Template($wtst, $userIdentifier);
      $wtu->id = $dbwWebToolsUsers->insertWebToolsUsers($wtu, true);
      $wtus[] = $wtu;
    }
    
    return $wtus;
  }

  
  private function getWebToolsUsers4Template($webToolsStdTempl, $userId)
  {
    $webToolsUsers = new \WebToolsUsers();
    $webToolsUsers->template_id = $webToolsStdTempl->template_id;
    $webToolsUsers->tool_id = $webToolsStdTempl->tool_id;
    $webToolsUsers->setUserIdentifier($userId);
    $webToolsUsers->validfrom = $webToolsStdTempl->validfrom;
    $webToolsUsers->validuntil = $webToolsStdTempl->validuntil;

    if (\DateTimeOperations::isDateTimeEmptyOrDefault($webToolsUsers->validfrom)) {
      $webToolsUsers->validfrom = \DateTimeOperations::getDateNow();
    }

    if (\DateTimeOperations::isDateTimeEmptyOrDefault($webToolsUsers->validuntil)) {
      $webToolsUsers->validuntil = '31.12.2099';
    }

    return $webToolsUsers;
  }

  private function insertPasswort($webUser, $pPasswortHash, $pHashversion, $auth_extern)
  {
    $dbwUser = new \DBWorkUser(1, true);
    $dbwUser->setHashedPassWD($webUser->login, $pPasswortHash, $pHashversion, $auth_extern);
  }
}