<?php
namespace Meramo\mrm_be;

//require '/var/phpmongodb/vendor/autoload.php';


// TODO: scheduler task alle 15 min welcher
// select x.deleted, x.disabled, x.source_path as source, x.target, x.target_statuscode as statusCode from sys_redirect as x where x.deleted = 0 and x.disabled = 0 order by x.updatedon DESC
// abfrägt und aber ohne deleted, disabled und mit timestamp nicht älter als 16 min ;)
// in key value array spielt und immer nur das aktuellste sourcepath-teil (updatedon) behält
// danach durchrequesten (deleted und disabled abfrage nicht vergessen ;) )
// target T3LINK überprüfen
// ganz zum schluss ein delete mongo query über deleted = 1 || disabled = 1 und dann passts

class Mongoer
{
  function __construct(){}

  public static function sendRequest($dataType, $action, $data){
//    $client = new \MongoDB\Client("mongodb://db:db@mongo:27017/");
    $client = new \MongoDB\Client($_ENV['FE_DATABASE_DSN']);
    $collection = null;
    if($dataType == "pages")
      $collection = $client->abi_local->pages;

    if($dataType == "search")
      $collection = $client->abi_local->searches;

    if($dataType == "topthemen")
      $collection = $client->abi_local->topthemens;

    if($dataType == "themaderwoche")
      $collection = $client->abi_local->themaderwoches;

    if($dataType == "security")
      $collection = $client->abi_local->pagesecurities;

    if($dataType == "abialtcache")
      $collection = $client->abi_local->abialtcaches;

    if($dataType == "menues")
      $collection = $client->abi_local->menues;

    if($dataType == "maintenance")
      $collection = $client->abi_local->maintenance;

    if($dataType == "redirects")
      $collection = $client->abi_local->redirects;

    if($dataType == "forwardings") 
      $collection = $client->abi_local->forwardings;
    
    if($dataType == "pdfgenjobs") 
      $collection = $client->abi_local->pdfgenjobs;
    if($dataType == "chatbot") 
      $collection = $client->abi_local->chatbot;

    if(!$collection) return self::log("no collection for senddata: ".$dataType);

    self::log("sendRequest ".$action." ".$dataType);
    if($action == "save"){
      $updateResult = $collection->updateOne(
          ['pageuid' => $data['pageuid']],
          ['$set' => $data],
          ['upsert' => true],
        );
    }
    if($action == "delete"){
      $collection->deleteOne(['pageuid' => $data['pageuid']]);
    }
    if($action == "deleteAll") {
      $collection->deleteMany([]);
    }
  }

  /* PRIVATES */
  private static function log($msg, $isString = true){
    if(!$isString){
      $msg = json_encode($msg, JSON_PRETTY_PRINT);
    }
    file_put_contents('/var/www/html/tuepotest/public/typo3temp/debug.log', $msg.PHP_EOL, FILE_APPEND);
  }

  /* Private function to drop a collection */
  public static function deleteAll($collection) {
    return $collection->deleteMany();
  }
}
