<?php

namespace web\admin\rigger;

class logfile {
    public static function json_init() {
        global $logpath;
        verifyfast();
        $files = scandir($logpath);
        $logfiles = array();
        foreach ($files as $file) {
            if ($file[0] == '.')
                continue;
            $logfiles[] = substr($file, 0, -4);
        }
        $ret['logfiles'] = $logfiles;
        return succjson($ret);
    }
    public static function json_clear() {
        global $db;
        global $logpath;
        $rsuser = verifyfast();
        if (nopower($db, $rsuser['id'], 'p555d'))
            return errjson('您未被授权操作');
        $post = new \ciy\post();
        $param = $post->get('param');
        $logfile = $logpath . $param . '.log';
        if (!file_exists($logfile))
            return errjson('文件不存在: ' . $logfile);
        file_put_contents($logfile, '');
        return succjson();
    }
    static function sse_viewlog($senddata, $sendevent) {
        global $logpath;
        $param = get('param');
        $logfile = $logpath . $param . '.log';
        if (!file_exists($logfile)) {
            $sendevent('文件不存在: ' . $logfile);
            return;
        }
        $bytesToRead = 10240;
        $handle = fopen($logfile, 'r');
        if (!$handle) {
            $sendevent('打开失败: ' . $logfile);
            return;
        }
        fseek($handle, 0, SEEK_END);
        $fileSize = ftell($handle);
        rewind($handle);
        $sendevent($param . ', Size:' . $fileSize);

        if ($fileSize > $bytesToRead) {
            fseek($handle, -$bytesToRead, SEEK_END);
            $content = '';
            while (!feof($handle) && strlen($content) < $bytesToRead) {
                $chunk = fread($handle, 1024);
                $content .= $chunk;
            }
        } else {
            $content = stream_get_contents($handle);
        }
        fclose($handle);
        foreach (explode("\n", $content) as $line) {
            $senddata($line);
        }
        while (true) {
            clearstatcache();
            $currentSize = filesize($logfile);
            if ($currentSize > $fileSize) {
                $handle = fopen($logfile, 'r');
                if ($handle) {
                    fseek($handle, $fileSize);
                    $content = '';
                    while (!feof($handle) && ftell($handle) < $currentSize) {
                        $content .= fread($handle, 1024);
                    }
                    fclose($handle);
                    foreach (explode("\n", $content) as $line) {
                        $senddata($line);
                    }
                }
                $fileSize = $currentSize;
            }
            $sendevent($param . ', Size:' . $fileSize);
            sleep(1);
        }
    }
}
