<?php

/**
 * Logger class
 * Implements the ILogger interface
 * @author Jerôme Brilland
 * @version 2.0
 * @copyright (c) 2010-2023, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class Logger implements ILogger {
    
    /**
     * @var string Log file name
     * @access private
     */
    private $filename = null;
    
    /**
     * @var string Logging level
     * @access private
     */
    private $level = null; 

    /**
     * Class constructor
     * @access public
     */
    public function __construct( string $filename, string $level ) {
        $this->filename = $filename;
        $this->level = $level;
    }
    
    /**
     * @param string $message
     * @access public
     */
    public function debug( string $message ) {
        if ( self::DEBUG == $this->level ) {
            $this->write( self::DEBUG, $message );
        }
    }
    
    /**
     * @param string $message
     * @access public
     */
    public function info( string $message ) {
        if ( self::INFO == $this->level || self::DEBUG == $this->level ) {
            $this->write( self::INFO, $message );
        }
    }
    
    /**
     * @param string $message
     * @access public
     */
    public function warn( string $message ) {
        if ( self::WARN == $this->level || self::INFO == $this->level || self::DEBUG == $this->level ) {
            $this->write( self::WARN, $message );
        }
    }
    
    /**
     * @param string $message
     * @access public
     */
    public function error( string $message ) {
        $this->write( self::ERROR, $message );
    }

    /**
     * @param string $message
     * @access public
     */
    public function write( string $level, string $message ) {
        $backtrace = debug_backtrace( 0, 2 );
        file_put_contents( $this->filename, [PHP_EOL, sprintf( '[%s] [%s] [%s] %s', date( 'Y-m-d H:i:s' ), $backtrace[sizeof( $backtrace ) == 1 ? 0 : 1]['file'], $level, $message )], FILE_APPEND );
    }

}
