<?php

namespace Mainto\RpcServer\RpcUtil\Tool\LogDriver;

use Illuminate\Support\Str;
use Mainto\RpcServer\RpcUtil\Tool\RpcLogInterface;
use Mainto\RpcServer\Protocol\Request\Request;
use Throwable;

abstract class LogDriveAbstract implements RpcLogInterface {
    protected bool $localMode = true;

    /**
     * LogDriveAbstract constructor.
     */
    public function __construct () {
        $this->localMode = config('app.env', "local") === "local";
    }

    /**
     * get trace info
     * @param int $offset
     * @return array
     */
    protected function getTraceInfo ($offset = 0) {
        $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 4);
        $file = $trace[2 + $offset]['file'] ?? "";
        $line = $trace[2 + $offset]['line'] ?? "unknown";
        $class = $trace[3 + $offset]['class'] ?? "";
        $type = $trace[3 + $offset]['type'] ?? "::";
        $function = $trace[3 + $offset]['function'] ?? "";

        if (Str::endsWith($function, "{closure}")) {
            $function = "{closure}";
        }

        return [
            "source" => "{$class}{$type}{$function} ($line)",
            "file"   => "{$file} ($line)",
        ];
    }


    /**
     * transform object to pretty json string
     *
     * @param $obj
     * @return string
     */
    protected function transObject ($obj) {
        return json_encode($obj, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    /**
     * log throwable error log
     *
     * @param $request
     * @param $source
     * @param Throwable $e
     */
    abstract public function logRequestThrowable (Request $request, Throwable $e, string $source = "");

    abstract public function logThrowable ($request, Throwable $e, string $source = "");

    /**
     * log info message
     *
     * @param $title
     * @param $message
     */
    abstract public function info (string $title, $message);

    /**
     * log debug message
     *
     * @param $title
     * @param $message
     */
    abstract public function debug (string $title, $message);

    /**
     * log notice message
     *
     * @param $title
     * @param $message
     */
    abstract public function notice (string $title, $message);

    /**
     * log warning message
     *
     * @param $title
     * @param $message
     */
    abstract public function warning (string $title, $message);

    /**
     * log error message
     *
     * @param $source
     * @param $title
     * @param $message
     */
    abstract public function error (string $title, $message);

    /**
     * log critical message
     *
     * @param $title
     * @param $message
     */
    abstract public function critical (string $title, $message);
}