<?php
namespace Meramo\mrm_be;

use \TYPO3\CMS\Core\Utility\GeneralUtility;
use \TYPO3\CMS\Core\Database\ConnectionPool;
use \TYPO3\CMS\Core\Database\Connection;


class DKZer
{
  private $connection;
  private $auth_token = null;
  private $fetched_data = null;

  function __construct(){
    $this->auth();
  }

  private function auth(){
    $url = "/auth";
    $data = array(
      'usr' => $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['usr'],
      'pwd' => $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['pwd']
    );
    $result = $this->sendRequest($url, $data);
    if($result["tok"]) $this->auth_token = $result["tok"];
  }

  private function sendRequest($url, $data){
    $url = $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['url'].$url;
    $data = json_encode($data);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Content-Length: ' . strlen($data))
    );
    $result = curl_exec($ch);

    if($result === FALSE) return null;
    return json_decode($result, TRUE);
  }

  private function log($msg, $isString = true){
    if(!$isString){
      $msg = json_encode($msg, JSON_PRETTY_PRINT);
    }
    file_put_contents('/var/www/html/typo3temp/debug.log', "--- DKZer ---".PHP_EOL.$msg.PHP_EOL, FILE_APPEND);
  }

  public function getSearchWords($codenrs) {
    $resultBerufe = $this->sendRequest(
        "/get/beruf",
        array(
          "tok" => $this->auth_token,
          "query" => array(
            "layer" => $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['layer'],
            "codenr" => array('$in' => preg_split('/( *),( *)/', $codenrs)),
          ),
          "select" => "suchworte.name_technisch",
        )
      )
    ;

    $resultSystematik = $this->sendRequest(
        "/get/systematik",
        array(
          "tok" => $this->auth_token,
          "query" => array(
            "layer" => $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['layer'],
            "codenr" => array('$in' => preg_split('/( *),( *)/', $codenrs)),
          ),
          "select" => "suchworte.name_technisch",
        )
      )
    ;

    if($resultBerufe === FALSE && $resultSystematik === FALSE) return null;
    $sws = array();
    if($resultSystematik)
      foreach($resultSystematik as $itm){
        foreach($itm["suchworte"] as $swo){
          $sws[] = $swo["name_technisch"];
        }
      }

    if($resultBerufe)
      foreach($resultBerufe as $itm){
        foreach($itm["suchworte"] as $swo){
          $sws[] = $swo["name_technisch"];
        }
      }
    $sws = array_unique($sws);
    return $sws;
  }

  public function getSearched($query){
    $result = $this->sendRequest(
        "/get/systematik",
        array(
          "tok" => $this->auth_token,
          "query" => array(
            "layer" => $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['layer'],
            "bezeichnung" => "***".$query
          ),
          "select" => "codenr suchworte bezeichnung"
        )
      )
    ;
    $result = array_merge($result, $this->sendRequest(
        "/get/beruf",
        array(
          "tok" => $this->auth_token,
          "query" => array(
            "layer" => $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['layer'],
            "bezeichnung" => "***".$query
          ),
          "select" => "codenr suchworte bezeichnung"
        )
      )
    );

    $ret = array();
    foreach($result as $itm){
      $ret[$itm['codenr']] = array('codenr' => $itm['codenr'], 'bezeichnung' => htmlspecialchars($itm['bezeichnung']), 'swcount' => sizeof($itm['suchworte']));
    }

    $keys = array_keys($ret);
    natsort($keys);
    $keys = array_values($keys);
    $ret2 = array();
    foreach($keys as $idx => $key){
      $ret2[] = $ret[$key];
    }

    return array("list" => array_values($ret2));
  }

  public function getLists($codenrs) {
    $resultBerufe = $this->sendRequest(
        "/get/beruf",
        array(
          "tok" => $this->auth_token,
          "query" => array(
            "layer" => $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['layer'],
            "codenr" => array('$in' => preg_split('/( *),( *)/', $codenrs)),
          ),
          "select" => "bezeichnung codenr suchworte.name",
        )
      )
    ;

    $resultSystematik = $this->sendRequest(
        "/get/systematik",
        array(
          "tok" => $this->auth_token,
          "query" => array(
            "layer" => $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['layer'],
            "codenr" => array('$in' => preg_split('/( *),( *)/', $codenrs)),
          ),
          "select" => "bezeichnung codenr suchworte.name",
        )
      )
    ;

    if($resultBerufe === FALSE && $resultSystematik === FALSE) return null;
    $sws = array();
    $berufe = array();
    if($resultSystematik)
      foreach($resultSystematik as $itm){
        $berufe[] = array( "codenr" => $itm["codenr"], "bezeichnung" => $itm["bezeichnung"] );
        foreach($itm["suchworte"] as $swo){
          $sws[] = $swo["name"];
        }
      }

    if($resultBerufe)
      foreach($resultBerufe as $itm){
        $berufe[] = array( "codenr" => $itm["codenr"], "bezeichnung" => $itm["bezeichnung"] );
        foreach($itm["suchworte"] as $swo){
          $sws[] = $swo["name"];
        }
      }
    $sws = array_unique($sws);
    return array("sws" => array_values($sws), "berufe" => array_values($berufe));
  }

  public function getBranch($path){
    $result = FALSE;
    if($path === "root")
        $result = $this->sendRequest(
            "/get/systematik",
            array(
              "tok" => $this->auth_token,
              "query" => array(
                "layer" => $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['layer'],
                '$expr' => array('$eq' => array(array('$strLenCP' => '$codenr'), 3))
              ),
              "select" => "codenr obercodenr suchworte bezeichnung"
            )
          )
        ;
    else {
      $result = $this->sendRequest(
          "/get/systematik",
          array(
            "tok" => $this->auth_token,
            "query" => array(
              "layer" => $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['layer'],
              "codenr" => "***^".$path."\\d$"
            ),
            "select" => "codenr obercodenr suchworte bezeichnung"
          )
        )
      ;
      $result = array_merge($result, $this->sendRequest(
          "/get/beruf",
          array(
            "tok" => $this->auth_token,
            "query" => array(
              "layer" => $GLOBALS['TYPO3_CONF_VARS']['MRM']['dkz']['layer'],
              "obercodenr" => $path
            ),
            "select" => "codenr obercodenr suchworte bezeichnung"
          )
        )
      );
    }

    $ret = array();
    foreach($result as $itm){
      $ret[$itm['codenr']] = array('codenr' => $itm['codenr'], 'obercodenr' => $itm['obercodenr'] ?  $itm['obercodenr'] : $path, 'bezeichnung' => htmlspecialchars($itm['bezeichnung']), 'swcount' => sizeof($itm['suchworte']));
    }

    $keys = array_keys($ret);
    natsort($keys);
    $keys = array_values($keys);
    $ret2 = array();
    foreach($keys as $idx => $key){
      $ret2[] = $ret[$key];
    }

    return $ret2;
  }
}
