<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

class AlternatingFileLogger
{
  private static $instance;
  public $filehandle = '';

  public function __construct()
  {
    $logPath = ConstantOperations::getPathForLog();
  }

  public static function getInstance()
  {
    if (self::$instance == null) {
      self::$instance = new AlternatingFileLogger();
    }

    return self::$instance;
  }

  public function getLogFilePath()
  {
    return $this->logFilePath;
  }

  public function getAlternateLogFilePath()
  {
    return $this->alternateLogFilePath;
  }

  public function setLogFile()
  {
    $logPath = ConstantOperations::getPathForLog();
    $debugfile = $logPath . 'debug.txt';
    $debugEinsfile = $logPath . 'debug1.txt';
    if (file_exists($debugfile) && file_exists($debugEinsfile)) {
      var_dump(fileatime($debugfile));
      var_dump(fileatime($debugEinsfile));
      if (fileatime($debugfile) > fileatime($debugEinsfile) && filesize($debugfile) < DEBUG_FILE_SIZE) {
        $this->filehandle = @fopen($debugfile, 'a');
      } elseif (filesize($debugEinsfile) < DEBUG_FILE_SIZE) {
        $this->filehandle = @fopen($debugEinsfile, 'a');
      } elseif (fileatime($debugfile) > fileatime($debugEinsfile)) {
        file_put_contents($debugEinsfile, '');
        @fclose($debugEinsfile);
        $this->filehandle = fopen($debugEinsfile, 'a');
      } elseif (fileatime($debugfile) < fileatime($debugEinsfile)) {
        file_put_contents($debugfile, '');
        $this->filehandle = fopen($debugfile, 'a');
      }
    } elseif (file_exists($debugfile)) {
      $this->filehandle = @fopen($debugfile, 'a');
    } elseif (file_exists($debugEinsfile)) {
      $this->filehandle = @fopen($debugEinsfile, 'a');
    }
  }

  public function log($pMessage, $pSeverity = 0, $showObjectsAndArraysInOneLine = false)
  {
    $this->setLogFile();
    if ($pSeverity >= Logger::getSeverity()) {
      if ($this->filehandle === false) { 
        return;
      }

      if (is_object($pMessage) || is_array($pMessage)) {
        if ($showObjectsAndArraysInOneLine) {
          $pMessage = DebugOperations::getVarString($pMessage, true);
        } else {
          $pMessage = "\n" . print_r($pMessage, true);
        }
      }

      $backtrace = debug_backtrace();
      $line = @$backtrace[1]['line'];
      $file = @pathinfo(@$backtrace[1]['file'], PATHINFO_BASENAME);
      $class = @$backtrace[2]['class'];
      $function = @$backtrace[2]['function'];
      
      fwrite($this->filehandle, date('Y.M.d H:i:s: ') . "($pSeverity) message='$pMessage' file='$file' class='$class' function='$function' line='$line'\r\n");
      fclose($this->filehandle);
    }
  }

  public static function logg($pMessage, $pSeverity = 0, $showObjectsAndArraysInOneLine = false)
  {
    $dateilogger = self::getInstance();
    $dateilogger->log($pMessage, $pSeverity, $showObjectsAndArraysInOneLine);
  }
}