<?php
/**
 * Represents the debug logger as represented through a file stream
 * @uses Monolog
 */

namespace PP\Loggers;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\JsonFormatter;

class LocalFileFactory
{
    const FILENAME = "panda-pay-api-wrapper.log";
    const LOGGER_NAME = "PandaPayAPIWrapper";

    /**
     * Creates a new logger with default values
     * @return Logger the logger
     */
    public static function createDefault()
    {
    	$file = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . "panda-pay-logs" . DIRECTORY_SEPARATOR;
        return static::create($file . static::FILENAME, static::LOGGER_NAME);
    }

	/**
	 * creates a new logger
	 * @param  string $file the filename of the log
	 * @param  string $loggerName the logger name
	 * @return Logger|null the logger or null if cannot write to file
	 */
	public static function create($file, $loggerName)
	{
		try {
			$path = dirname($file);

			if (!file_exists($path))
				if (is_writable($path))
					@mkdir($path);
				else
					return null; // cannot create directory

			if (file_exists($file) && !is_writable($file))
				return null;

			// Create the handler
			$stream = new StreamHandler( $file );
			$stream->setFormatter( new JsonFormatter() );

			// Create the stream
			$logger = new Logger( $loggerName );
			$logger->pushHandler( $stream );

			return $logger;
		} catch (\Exception $e) {
			return null;
		}
	}

}
