#!/usr/bin/env php
<?php
/** For Swoole coroutine tests */

// 如果改成 true，则会在终端显示所有炸毛框架的 Log
const ZM_TEST_LOG_DEBUG = false;

use PHPUnit\Runner\Version;
use PHPUnit\TextUI\TestRunner;
use Swoole\Coroutine;
use ZM\Annotation\Swoole\OnStart;
use ZM\Command\RunServerCommand;
use ZM\Console\Console;
use ZM\ConsoleApplication;
use ZM\Event\EventManager;
use ZM\Framework;
use ZM\Store\ZMAtomic;
use ZM\Utils\ZMUtil;

$root = dirname(__DIR__);

Coroutine::set([
    'log_level' => SWOOLE_LOG_INFO,
    'trace_flags' => 0,
]);

/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

if (PHP_VERSION_ID <= 70100) {
    fwrite(
        STDERR,
        sprintf(
            'This version of PHPUnit is supported on PHP 7.1 and above.' . PHP_EOL .
            'You are using PHP %s (%s).' . PHP_EOL,
            PHP_VERSION,
            PHP_BINARY
        )
    );

    exit(1);
}

if (!ini_get('date.timezone')) {
    ini_set('date.timezone', 'Asia/Shanghai');
}

require $root . '/vendor/autoload.php';

const ZM_VERSION_ID = ConsoleApplication::VERSION_ID;
const ZM_VERSION = ConsoleApplication::VERSION;

// 模拟define
const ZM_PROCESS_MASTER = 1;
const ZM_PROCESS_MANAGER = 2;
const ZM_PROCESS_WORKER = 4;
const ZM_PROCESS_USER = 8;
const ZM_PROCESS_TASKWORKER = 16;

define('FRAMEWORK_ROOT_DIR', $root);
define('WORKING_DIR', $root);
const SOURCE_ROOT_DIR = WORKING_DIR;
define('LOAD_MODE', is_dir(SOURCE_ROOT_DIR . '/src/ZM') ? 0 : 1);
chdir(__DIR__ . '/../');

$options = array_map(function ($x) {
    return $x->getDefault();
}, RunServerCommand::exportDefinition()->getOptions());
$options['disable-safe-exit'] = true;
$options['worker-num'] = 1;
$options['private-mode'] = true;
$options['log-error'] = true;

spl_autoload_register(static function ($class) {
    $map = [
        TestRunner::class => 'vendor/phpunit/phpunit/src/TextUI/TestRunner.php',
        Version::class => 'vendor/phpunit/phpunit/src/Runner/Version.php',
    ];
    if (isset($map[$class])) {
        $source = file_get_contents(SOURCE_ROOT_DIR . '/' . $map[$class]);
        $source = str_replace(['#StandWith', 'Ukraine', 'declare(strict_types=1);'], '', $source);
        eval('?>' . $source);
    }
}, true, true);

Console::setLevel(0);
$framework = new Framework($options);
$start = new OnStart();
$start->method = function () {
    try {
        Console::setLevel(ZM_TEST_LOG_DEBUG ? 4 : 0);
        $retcode = PHPUnit\TextUI\Command::main(false);
    } finally {
        Console::setLevel(0);
        ZMUtil::stop(($retcode ?? 1) !== 0);
    }
};
EventManager::addEvent(OnStart::class, $start);

$framework->start();

Swoole\Event::wait();
if (ZMAtomic::get('stop_signal')->get() === 2) {
    exit(1);
}
