<?php

/**
 * @package safi
 */

namespace WPJoli\SAFI;

use WPJoli\SAFI\Application;

class Log
{

    const ALERT = 'alert';
    const CRITICAL = 'critical';
    const DEBUG = 'debug';
    const EMERGENCY = 'emergency';
    const ERROR = 'error';
    const INFO = 'info';
    const NOTICE = 'notice';
    const WARNING = 'warning';

    protected $file;
    protected $log;
    protected $app;

    public function __construct(Application $app)
    {
        $this->app = $app;
        $this->file = $this->app->path('safi-debug.log');
    }

    public function log($message, $level = 'info', $logfile = null, $helper = false)
    {
        $entry = $this->buildLogEntry($level, $message, $helper);

        $log = $logfile ? $logfile : $this->file; // full file path including filename
        $dir = dirname($log); // get directory path only

        // Ensure directory exists
        if (! file_exists($dir)) {
            wp_mkdir_p($dir);
        }

        // Write log entry
        file_put_contents($log, $entry, FILE_APPEND | LOCK_EX);
    }

    protected function buildLogEntry($level, $message, $helper = false)
    {
        $backtrace = $this->getBacktrace($helper);
        return sprintf(
            '[%s|%s] %s: %s' . PHP_EOL,
            current_time('mysql'),
            substr($backtrace, strpos($backtrace, Application::ID)),
            // "", //substr($backtrace, strpos($backtrace, Application::ID)),
            strtoupper($level),
            $message
        );
    }

    /**
     * @return void|string
     */
    protected function getBacktrace($helper = false)
    {

        $depth = $helper ? 5 : 4; // if the log function is wrapper in helper function, we need to get one more level deep for the backtrace
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $depth);
        // echo '<pre>';
        // print_r($backtrace);
        // echo '</pre>';
        $entry = array_pop($backtrace);
        $path = str_replace([$this->app->path('plugin/'), $this->app->path()], '', $entry['file']);
        return $path . ':' . $entry['line'];
    }
}
