<?php


namespace Mainto\RpcServer\Log;

use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;

class LogHandler extends AbstractProcessingHandler {
    /**
     * @var resource
     */
    private static $stream = null;

    public function __construct ($level = Logger::DEBUG, $bubble = true) {
        parent::__construct($level, $bubble);

        if (!static::$stream) {
            static::init(storage_path("logs/service"), "laravel", '');
        }
    }

    public static function init ($dir, string $logId, string $timePreFormat = 'His') {
        if (config('logging.default') == 'service') {
            self::closeStream();
            @mkdir($dir, 0777, true);

            if ($timePreFormat) {
                $time = now()->format($timePreFormat);
                self::$stream = fopen("{$dir}/{$time}-{$logId}.log", 'a');
            } else {
                self::$stream = fopen("{$dir}/{$logId}.log", 'a');
            }
        }
    }

    private static function closeStream () {
        if (self::$stream !== null) {
            fclose(self::$stream);
            self::$stream = null;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function handle (array $record) {
        if (!$this->isHandling($record)) {
            return false;
        }

        if ($record['datetime'] instanceof \DateTime) {
            $record['datetime'] = $record['datetime']->format("U.u");
        }

        $this->write($record);

        return false === $this->bubble;
    }

    protected function write (array $record) {
        fwrite(self::$stream, json_encode($record)."\n");
    }

    public function close () {
        self::closeStream();
    }
}