package fiko_socket_io

import (
	"log"
	"time"

	fikoMongo "server/sistem/fiko_mongo"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/adaptor"
	EIOLog "github.com/zishang520/engine.io/v2/log"
	"github.com/zishang520/engine.io/v2/types"
	"github.com/zishang520/socket.io/v2/socket"
)

var FikoSocketIo *socket.Server

func Init(app *fiber.App) {
	EIOLog.DEBUG = true
	socketioSettings := socket.DefaultServerOptions()
	socketioSettings.SetServeClient(true)
	// c.SetConnectionStateRecovery(&socket.ConnectionStateRecovery{})
	socketioSettings.SetAllowEIO3(true)
	socketioSettings.SetAllowUpgrades(false)

	socketioSettings.SetPingInterval(300 * time.Millisecond)
	socketioSettings.SetPingTimeout(200 * time.Millisecond)
	socketioSettings.SetMaxHttpBufferSize(1000000)
	socketioSettings.SetConnectTimeout(1000 * time.Millisecond)
	socketioSettings.SetCors(&types.Cors{
		Origin:      "*",
		Credentials: true,
	})
	FikoSocketIo = socket.NewServer(nil, nil)
	FikoSocketIo.On("connection", func(clients ...interface{}) {
		client := clients[0].(*socket.Socket)
		log.Println("Bağlandııı Goooooooooooo", client.Id())

		client.On("message", func(args ...interface{}) {
			client.Emit("message-back", args...)
			log.Println(args)
			s, _ := fikoMongo.GetSession().Get()
		})
		client.Emit("auth", client.Handshake().Auth)

		client.On("message-with-ack", func(args ...interface{}) {
			ack := args[len(args)-1].(socket.Ack)
			ack(args[:len(args)-1], nil)
		})

		client.On("disconnect", func(clients ...interface{}) {
			log.Println("Koptu Goooooooooooo", client.Id())
		})

	})

	//
	app.Get("/socket.io", adaptor.HTTPHandler(FikoSocketIo.ServeHandler(socketioSettings)))
	app.Post("/socket.io", adaptor.HTTPHandler(FikoSocketIo.ServeHandler(socketioSettings)))
}
