<?php

namespace Lib;


/**
 * 日志文件
 * @author:dc
 * @time 2023/3/14 10:26
 * Class Log
 * @package Lib
 */
class Log {


    /**
     * @var array
     */
    public array $filename = [];

    /**
     * @var array
     */
    public array $message = [];

    /**
     * @var self
     */
    private static self $instance;

    /**
     * Log constructor.
     */
    public function __construct()
    {
        $this->setFilename();
    }

    /**
     * 追加日志内容
     * @param string $message
     * @author:dc
     * @time 2023/3/14 10:45
     */
    public static function append(string $message, $filename = null){

        if($filename){
            self::getInstance()->setFilename($filename);
        }

        self::getInstance()->message[$filename ? md5($filename) : 'default'][] = $message;

    }


    /**
     * @return Log
     */
    public static function getInstance(): Log
    {
        if (empty(static::$instance)){
            static::$instance = new Log();
        }

        return self::$instance;
    }

    /**
     * 设置日志文件
     * @param $filename
     * @author:dc
     * @time 2023/3/14 11:11
     */
    private function setFilename($filename=null){
        if($filename){
            $this->filename[md5($filename)] = $filename;
        }else{
            $this->filename['default'] = $filename = LOG_PATH.'/'.app()->nowDate().'.error.log';
        }

        // 创建目录
        if(!is_dir(dirname($filename))){
            @mkdir(dirname($filename),0755,true);
        }

    }

    /**
     * 写入日志
     * @author:dc
     * @time 2023/3/14 10:45
     */
    public function write(){

        foreach ($this->filename as $key=>$fn){
            if(!empty($this->message[$key])){

                array_unshift($this->message[$key],app()->nowDateTime());
                $this->message[$key][] = PHP_EOL;

                @file_put_contents(
                    $fn,
                    implode(PHP_EOL."\t",$this->message[$key]),
                    FILE_APPEND
                );
                $this->message[$key] = [];
            }

        }

    }

}