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

class MaxFileSizeLogger extends DateiLogger
{
  private static $instance;

  
  private $maxFileSize;

  public function getMaxFileSize()
  {
    return $this->maxFileSize;
  }

  public function setMaxFileSize($pMaxFileSize)
  {
    $this->maxFileSize = $pMaxFileSize;
  }

  public function __construct($pMaxFileSize)
  {
    parent::__construct();
    if ($pMaxFileSize <= 0) {
      throw new Exception('$pMaxFileSize muss größer als 0 sein');
    }
    $this->maxFileSize = $pMaxFileSize;
    $logFilePath = ConstantOperations::getPathForLog() . 'debug.txt';
    $this->setLogFilePath($logFilePath);
  }

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

    return self::$instance;
  }

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

  public function trimFile()
  {
    $logfile = $this->getLogFilePath();

    $size = filesize($logfile);
    if ($size === false) {
      return;
    }

    if ($size <= $this->maxFileSize) {
      return;
    }

    $overhead = $size - $this->maxFileSize;

    $filehandle = fopen($logfile, 'r+');
    if ($filehandle === false) {
      return;
    }

    fseek($filehandle, $overhead, SEEK_SET);
    $content = fread($filehandle, $this->maxFileSize);
    fseek($filehandle, 0, SEEK_SET);
    ftruncate($filehandle, 0);
    fwrite($filehandle, $content);
    fclose($filehandle);
  }
}