<?php

namespace Lucent\Http\Controller;

use App\Http\Controllers\Controller;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Lucent\Channel\ChannelService;
use Lucent\Command\CommandRepo;
use Lucent\Command\CommandService;
use Lucent\Svelte\Svelte;

class BuildController extends Controller
{
    public function __construct(
        private readonly Svelte         $svelte,
        private readonly ChannelService $channelService,
        private readonly CommandService $commandService,
        private readonly CommandRepo    $commandRepo,
    )
    {
    }

    public function build(Request $request)
    {
        $commandSignature = $request->route("signature");
        $this->commandService->run($commandSignature);

    }

    public function report(Request $request): View
    {
        $commandSignature = $request->route("signature");
        $command = $this->channelService->channel->commands->firstWhere("signature", $commandSignature);

        return $this->svelte->render(
            layout: "channel",
            view: "buildReport",
            title: $command->name,
            data: [
                "command" => $command,
            ]
        );
    }

    public function reportSource(Request $request)
    {
        $commandSignature = $request->route("signature");
        return response()->stream(function () use ($commandSignature) {
            while (true) {

                $commandLogItem = $this->commandRepo->findBySignature($commandSignature);
                $data["date"] = date("Y-m-d H:i:s");
                $data["logs"] = $commandLogItem->logs ?? "";
//                $lines = explode("\n",$data["logs"]);

                echo 'data: ' . json_encode($data);
                echo "\n\n";

                ob_flush();
                flush();
                logger($this->commandService->commandIsRunning($commandLogItem->pid));
                if (!$this->commandService->commandIsRunning($commandLogItem->pid)) {
                    break;
                }

                // Break the loop if the client aborted the connection (closed the page)
                if (connection_aborted()) {
                    break;
                }
                sleep(1); // 50ms
            }
        }, 200, [
            'Cache-Control' => 'no-cache',
            'X-Accel-Buffering' => 'no',
            'Content-Type' => 'text/event-stream',
        ]);
    }

}
