<?php
namespace Meramo\mrm_be;

class Mongoer
{
  function __construct(){}

  public static function sendRequest($dataType, $action, $data){
      $mongodburl = $_ENV['FE_DATABASE_DSN'];
      $mongodbdb = $_ENV['FE_DATABASE'];
    $client = new \MongoDB\Client($mongodburl);
    $collection = null;
    if($dataType == "pages")
      $collection = $client->$mongodbdb->pages;

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

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

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

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

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

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

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

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

    if($dataType == "forwardings") 
      $collection = $client->$mongodbdb->forwardings;
    
    if($dataType == "pdfgenjobs") 
      $collection = $client->$mongodbdb->pdfgenjobs;
    if($dataType == "chatbot") 
      $collection = $client->$mongodbdb->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('/tmp/t3mongoerdebug.log', $msg.PHP_EOL, FILE_APPEND);
  }

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