<?php


namespace CCDN\Helpers\Logger;

use CCDN\Helpers\Settings;
use DirectoryIterator;

/**
 * Class LogWriter
 *
 * @package CCDN\Helpers\Logger
 */
class Log
{

    private $separator = PHP_EOL.'-------------------------------------------------'.PHP_EOL;

    /**
     * Logs with an arbitrary level.
     *
     * @param  mixed  $type
     * @param  string  $message
     *
     * @return void
     */
    public function write($type, $message)
    {
        $data = '';
        $fileName = Settings::LOG_PATH.'/'.$type.'_'.date('Y-m-d').'.log';

        if (!is_file($fileName)) {
            global $config;
            $data .= '/*'.PHP_EOL.'|------------------------- INFO --------------------------'.PHP_EOL.'';
            $data .= '| Plugin version : '.Settings::PLUGIN_VERSION.PHP_EOL;
            $data .= '| PHP version : '.PHP_VERSION.PHP_EOL;
            $data .= '| PHP memory limit : '.ini_get('memory_limit').PHP_EOL;
            $data .= '| DLE version: '.$config['version_id'].PHP_EOL;
            $data .= '|---------------------------------------------------------'.PHP_EOL.'/';
            $data .= $this->separator;
        }

        $data .= '['.date('H:i:s').'] '.$message.$this->separator;

        file_put_contents($fileName, $data, FILE_APPEND | LOCK_EX);
    }

    /**
     * @return array
     */
    public function getLogList()
    {
        $logList = [];
        $logFiles = new DirectoryIterator(Settings::LOG_PATH);
        foreach ($logFiles as $logFile) {
            if ($logFile->isFile() && $logFile->getFilename() !== '.htaccess') {
                $logList[] = $logFile->getFilename();
            }
        }
        return $logList;
    }

    /**
     * @param  string  $name
     *
     * @return string|null
     */
    public function getLog($name)
    {
        if (!file_exists(Settings::LOG_PATH.'/'.$name)) {
            return null;
        }

        $log = @file_get_contents(Settings::LOG_PATH.'/'.$name);

        if ($log === false) {
            return null;
        }

        return $log;
    }
}
