<?php

declare(strict_types=1);

namespace Atdt\Screens;

use Atdt\Ctx;
use Atdt\In;
use Atdt\Pipe;
use Atdt\Screen;
use Atdt\ScreenEngine;

/**
 * Who's online (SPEC §10.6): active sessions with node, handle, and the
 * current screen's friendly name (screens self-describe via describe()).
 */
final class WhosOnlineScreen implements Screen
{
    public function describe(): string
    {
        return "Checking who's online";
    }

    public function enter(Ctx $c): array
    {
        $sessions = $c->db()->all(
            'SELECT s.node, s.state, s.user_id, u.handle
             FROM sessions s LEFT JOIN users u ON u.id = s.user_id
             WHERE s.active = 1 AND s.kick = 0 ORDER BY s.node'
        );
        $o = $c->out()->cls();
        $o->at(2, 1)->txt($c->center($c->tstr('online.title')));
        $o->at(3, 1)->fg(8)->txt($c->center(str_repeat('─', 50)))->reset();
        $o->at(5, 14)->txt($c->tstr('online.columns'));
        $row = 7;
        foreach ($sessions as $s) {
            $handle = $s['user_id'] === null
                ? \Atdt\Pipe::strip($c->tstr('online.logging_in'))
                : (string)$s['handle'];
            $me = (int)$s['node'] === $c->node() ? '|14*|07' : ' ';
            $o->at($row++, 14)->txt($c->pipe(sprintf(
                '%s |03%2d  |15%-20s |07%s',
                $me,
                (int)$s['node'],
                Pipe::escape(mb_strimwidth($handle, 0, 20)),
                Pipe::escape(ScreenEngine::describeState((string)$s['state']))
            )));
            if ($row > 19) {
                break;
            }
        }
        $o->at(21, 1)->txt($c->center($c->tstr('nua.press_any_key')));
        return [$c->ansi($o->reset()->str()), $c->hotkey()];
    }

    public function input(Ctx $c, In $in): array
    {
        if ($in->kind !== 'key') {
            return [$c->bell()];
        }
        return strtoupper((string)$in->key) === '?' ? $this->enter($c) : $c->pop();
    }
}
