<?php

namespace Workerman\Lib;

use Workerman\Worker;

$bot_loop = new Worker();
$bot_loop->count = 1;
$bot_loop->name = 'DeleteLog';

function deleteOldLogs($baseDir) {
  $currentTime = time();
  if ($handle = opendir($baseDir)) {
    while (false !== ($entry = readdir($handle))) {
      if ($entry == '.' || $entry == '..') continue;
      $path = $baseDir . '/' . $entry;
      if (is_dir($path) && preg_match('/^\d{8}$/', $entry)) {
        $dateTimestamp = strtotime($entry);
        $intervalDays = floor(($currentTime - $dateTimestamp) / (60 * 60 * 24));
        if ($innerHandle = opendir($path)) {
          while (false !== ($file = readdir($innerHandle))) {
            if ($file == '.' || $file == '..') continue;
            if (preg_match('/^level(\d+)\.txt$/', $file, $matches)) {
              $level = intval($matches[1]);
              $daysToKeep = $level * 3;
              if ($intervalDays > $daysToKeep) {
                $logFile = $path . '/' . $file;
                if (file_exists($logFile)) {
                  unlink($logFile);
                }
              }
            }
          }
          closedir($innerHandle);
        }
        if (count(scandir($path)) == 2) { // 目录为空（只有.和..）
          rmdir($path);
        }
      }
    }
    closedir($handle);
  }
}

function DeleteLogFunc()
{
  $baseDirectory = '../bot/logs';
  deleteOldLogs($baseDirectory);
}

$bot_loop->onWorkerStart = function () {
  DeleteLogFunc();
  Timer::add(60 * 60, function () {
    DeleteLogFunc();
  });
};
