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

namespace Kufer\Web\KuferTools\Mitarbeiter\AdressInfo\UpdateAdress\HandleAdressUpdate;

use Kufer\Web\Classes\Addfunctions\Guid;
use Kufer\Web\Classes\Identifier\Identifier;
use Kufer\Web\KuferTools\Utils\AdressHandler\AdressUpdater;

class HandleAdressUpdateUseCase extends \Kufer\Web\KuferTools\Basis\UseCase\ToolUseCase
{
  public function __construct($request)
  {
    parent::__construct($request, new HandleAdressUpdateResponse());
  }

  public static function getToolSectionId()
  {
    return 58;
  }

  public static function getToolId()
  {
    return \ToolsAPI::TOOL_ADRESSINFO_MA;
  }

  public function hasAccess($pToolSectionId = null)
  {
    if (!parent::hasAccess(410)) {
      return false;
    }
    if (!$this->isRechtAllowed('410.0.1')) { 
      return false;
    }

    if (empty(\DBWorkAdresse::getDefaultInstance()->getAdresse($this->getRequestedIdentifier())->id)) {
      return false;
    }
    
    
    
    return true;
  }

  protected function getRequestedId()
  {
    return $this->request->anr;
  }

  protected function getRequestedGuid(): ?Guid
  {
    if (empty($this->request->aguid)) {
      return null;
    }

    return new Guid($this->request->aguid);
  }

  protected function getRequestedIdentifier(): ?Identifier
  {
    return new Identifier($this->getRequestedId(), $this->getRequestedGuid());
  }

  public function action()
  {
    $adressUpdater = new AdressUpdater($this->toolSettings);
    $origAdresse = $this->getAdresse();
    list($statusCode, $wrongFields) = $adressUpdater->handleAdressUpdate($this->request->wssHandler, $this->request->columnValues, $origAdresse);
    \SessionOperations::setVarValueWTIntern('newAdrStatusCode', $statusCode);
    \SessionOperations::setVarValueWTIntern('newAdrWrongFields', $wrongFields);

    return $this->getResponse();
  }

  protected function getAdresse(): \Adresse
  {
    $dbwAdresse = new \DBWorkAdresse(1, true);

    return $dbwAdresse->getAdresse($this->getRequestedIdentifier(), true);
  }

  protected function getResponse()
  {
    $this->response->anr = $this->getRequestedId();
    $this->response->aguid = $this->getRequestedGuid();

    return $this->response;
  }
}

class HandleAdressUpdateRequest
{
  public $anr;
  public $aguid;
  public $adressUpdate;
  public $columnValues;
  public $wssHandler;
}

class HandleAdressUpdateResponse extends \Kufer\Web\KuferTools\Basis\UseCase\ToolResponse
{
  public $anr;
  public $aguid;
}