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

namespace Kufer\Web\KuferTools\Dozent\HonorarAbnahme\HonorarBelege;

use Kufer\Web\Classes\Datamodul\HonorarAbnahme;

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

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

  public static function getToolSectionId(): int
  {
    return 784;
  }

  public function hasAccess($pToolSectionId = null)
  {
    if (!parent::hasAccess($pToolSectionId)) {
      return false;
    }

    if (!$this->request->isRefresh && !$this->request->isXsrfOk) {
      return false;
    }

    if (!\CleanOperations::isNatural($this->request->id)) {
      return false;
    }
    if (!\CleanOperations::isNatural($this->request->lfdnr)) {
      return false;
    }

    $this->request->id = (int)$this->request->id;
    $this->request->lfdnr = (int)$this->request->lfdnr;

    if (is_null($this->findHonorarAbnahme())) {
      return false;
    }

    return true;
  }

  
  private $cacheHonorarAbnahme;

  private function findHonorarAbnahme(): ?HonorarAbnahme
  {
    if (is_null($this->cacheHonorarAbnahme)) {
      try {
        $this->cacheHonorarAbnahme = \HonorarAbnahmeAPI::getHonorarAbnahmenById(
          $this->getUser()->getDnrIdentifier(),
          $this->request->id
        );
      } catch (\AbgleichApiException $ex) {
        \Logger::loggException($ex, 100);
        $this->response->error = true;

        return null;
      }
    }

    return $this->cacheHonorarAbnahme;
  }

  private $cacheDatDoc;

  private function findDatDoc()
  {
    if (is_null($this->cacheDatDoc)) {
      try {
        $this->cacheDatDoc = \DatDocAPI::getDokumentFromDmz($this->createDatDocFilter($this->findHonorarAbnahme(), $this->request->lfdnr));
      } catch (\AbgleichApiException $ex) {
        \Logger::loggException($ex, 100);

        return null;
      }
    }

    return $this->cacheDatDoc;
  }

  public function action()
  {
    $this->response->file = $this->findDatDoc();

    return $this->response;
  }

  private function createDatDocFilter(HonorarAbnahme $honorarAbnahme, int $lfdnr): \Dat_doc
  {
    $result = new \Dat_doc();
    $result->lfdnr = $lfdnr;
    $result->hon_abnahme_id = $honorarAbnahme->id;

    return $result;
  }
}