#!/usr/bin/env php
<?php

use Porter\Terminal;

use function porter\copy_dir_to;

include $_composer_autoload_path ?? __DIR__ . '/../vendor/autoload.php';

switch ($argv[1] ?? null) {
    case 'template:laravel':
        $destination = rtrim($argv[2] ?? './websocket', '/\\');

        @mkdir($destination);

        $path = realpath($destination);

        copy_dir_to(__DIR__ . '/../examples/laravel', $path);

        unlink($path . '/README.md');

        Terminal::print('{bg:cyan}{text:white} 📁 Placed to ' . $path);
        break;

    case 'make:event':
        if (!str_ends_with($argv[2], '.php')) {
            $argv[2] .= '.php';
        }

        if (file_exists($argv[2])) {
            Terminal::print("{bg:red}{text:white}Event class '{$argv[2]}' already exists.");
            break;
        }

        $dirPath = dirname($argv[2]);

        if (!file_exists($dirPath)) {
            mkdir($dirPath, 0666, true);
        }

        $type = $argv[3] ?? str_replace('.php', '', mb_strtolower(basename($argv[2])));

        $eventClass = <<<EOF
        <?php

        use Porter\Server;
        use Porter\Payload;
        use Porter\Connection;
        use Porter\Events\AbstractEvent;

        return new class extends AbstractEvent
        {
            public string \$type = '$type';

            protected array \$rules = [];

            public function handle(Connection \$connection, Payload \$payload, Server \$server)
            {
                //
            }
        };
        EOF;

        file_put_contents($argv[2], $eventClass);
        break;

    default:
        Terminal::print('{text:darkGreen}List of commands:');
        Terminal::print('    {text:white}template:laravel [?destination] {reset}- Integration to Laravel project. [e.g. template:laravel ./websocket]');
        Terminal::print('    {text:white}make:event [path] [?type] {reset}- Make event class. [e.g. make:event ./websocket/events/ping.php ping]');
        break;
}