package api

import (
	"context"
	"fmt"
	"time"

	"nhooyr.io/websocket"
	"nhooyr.io/websocket/wsjson"

	"codefirst.iut.uca.fr/git/thomas.bellembois/codefirst-dockerrunner-common/v2/callbacks"
	"codefirst.iut.uca.fr/git/thomas.bellembois/codefirst-dockerrunner-common/v2/errors"
	"codefirst.iut.uca.fr/git/thomas.bellembois/codefirst-dockerrunner-common/v2/messages"
	"codefirst.iut.uca.fr/git/thomas.bellembois/codefirst-dockerrunner-common/v2/models"
)

func Pong(ctx context.Context, wsConnection *websocket.Conn) {
	message := messages.WSMessage{
		Action: callbacks.AfterPingCallback,
	}

	err := wsjson.Write(ctx, wsConnection, message)
	if err != nil {
		fmt.Println(err)
	}
}

func Test(ctx context.Context, wsConnection *websocket.Conn, codeFirstContainer models.CodeFirstContainer) {
	counter := 0

	for counter < 5 {
		message := messages.WSMessage{
			Action:  callbacks.AfterTestCallback,
			Message: "hello from server",
		}

		err := wsjson.Write(ctx, wsConnection, message)
		if err != nil {
			fmt.Println(err)
		}

		counter++

		time.Sleep(2 * time.Second)
	}
}

func TestError(ctx context.Context, wsConnection *websocket.Conn, codeFirstContainer models.CodeFirstContainer) {
	sendError(ctx, wsConnection, errors.AppError{Type: errors.CreateContainer, SourceErrorMessage: "test error"})
}
