package workers

import (
	"agent/client"
	"agent/commons/debug"
	"agent/modules/console/api"
	"context"
	"strings"
	"time"

	"github.com/google/uuid"
)

func OutputWorker(ctx context.Context, consoleManager *ConsoleManager) {
	cl := client.ExtractClient(ctx)
	for {
		select {
		case <-ctx.Done():
			return
		case <-time.After(time.Second * 1):
			if !cl.IsAuthorized() {
				continue
			}
			for _, console := range consoleManager.List() {
				consoleUuid := console.Uuid()
				lines := console.PopOutput()
				if len(lines) == 0 {
					continue
				}

				debug.Logf("%s\n", strings.Join(lines, ""))

				if err := api.AgentConsoleSetOutput(ctx, cl, consoleUuid, uuid.Nil, lines); err != nil {
					debug.Log(err)
				}
			}
		}
	}
}
