package fiko_socket_io

import (
	"log"
	"time"

	"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(false)
	// c.SetConnectionStateRecovery(&socket.ConnectionStateRecovery{})
	socketioSettings.SetAllowEIO3(true)
	socketioSettings.SetAllowUpgrades(false)
	socketioSettings.SetTransports(types.NewSet("websocket"))

	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)
		ClientBaglandi(client)
	})

	//
	app.Get("/socket.io/", adaptor.HTTPHandler(FikoSocketIo.ServeHandler(socketioSettings)))
	app.Post("/socket.io/", adaptor.HTTPHandler(FikoSocketIo.ServeHandler(socketioSettings)))
}

func ClientBaglandi(client *socket.Socket) {
	log.Println("Bağlandııı Goooooooooooo", client.Id())

	client.On("message", func(args ...interface{}) {
		client.Emit("message-back", args...)
		log.Println(args)

	})
	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())
	})
	client.On("connect_error", func(args ...interface{}) {
		log.Println("Koptu Goooooooooooo", args)
	})
}
