package common

import (
	"fmt"
	"net/http"

	api "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api"
	// errs "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs"
	"github.com/gorilla/websocket"
	context "github.com/kataras/iris/v12/context"
)

var (
	HubInstance = NewHub()
	upgrader        = websocket.Upgrader{} // use default options
)

func init() {
	upgrader.CheckOrigin = func(r *http.Request) bool { return true }
	//Inicializa a thread do servidor de chat
	go HubInstance.Run()
}

// Converte a requisição em um ws.
/*
{
    "id": "ws",
    "entity": "Thread",
    "type": "",
    "path": "/ws",
    "template": "implement",
    "beforePersistAction": false,
    "httpMethod": "GET",
    "description": "Converte a requisição em um ws.",
    "response": "Thread",
    "request": "",
    "scopes": [],
    "middlewares": [],
    "postresponse": null,
    "parameterOrder": [],
    "parameters": [],
    "parametersmap": {}
}
*/
func WsUpgrader(ctx context.Context) {
	var (
		con, err = upgrader.Upgrade(ctx.ResponseWriter(), ctx.Request(), nil)
	)
	if err != nil {
		fmt.Println("error:", err)
		return 
	}

	client := &WsClient{
		Id:   api.Q(ctx, "i", ""),
		Hub:  HubInstance,
		Conn: con,
		Send: make(chan *Event, 256),
	}

	HubInstance.Register <- client

	client.Handle()
	return 
}
