package main

import (
	"log"
	"os"
	"time"

	"git.ali33.ru/fcg-xvii/net/v3/http/engine"
	"github.com/gorilla/websocket"
)

func NewWSEngine(base engine.Engine, urlPath string) *WSEngine {
	res := &WSEngine{
		Engine:   base,
		urlPath:  urlPath,
		clients:  NewWSClients(),
		listener: make(chan *WSClient),
	}
	return res
}

type WSEngine struct {
	engine.Engine
	urlPath  string
	clients  *WSClients
	upgrader websocket.Upgrader
	listener chan *WSClient
}

func (s *WSEngine) Listener() <-chan *WSClient {
	return s.listener
}

func (s *WSEngine) Exec(req *engine.Request, resp *engine.Response) {
	if req.URL.Path == s.urlPath {
		if conn, err := s.upgrader.Upgrade(resp.ResponseWriter(), req.Request, nil); err == nil {
			cl := s.clients.clientConnected(conn)
			select {
			case s.listener <- cl:
			default:
			}
		}
		return
	}
	s.Engine.Exec(req, resp)
}

/////////////////////////////

func NewApplication(addr string) engine.Engine {
	params := map[string]any{
		"addr": addr,
	}
	app := engine.NewEngineBase(params, nil, "html")
	wsApp := NewWSEngine(app, "/api")

	go func() {
		for cl := range wsApp.Listener() {
			//log.Println("CL.....", cl)
			go func(c *WSClient) {
				//log.Println("CL-READ")
				for mes := range c.Read() {
					log.Println("------>", mes)
					messageIncoming(mes)
				}
				//log.Println("CL-CLOSE")
				t := time.NewTimer(time.Second * time.Duration(downTime))
				<-t.C
				if c.clients.Size() == 0 {
					os.Exit(0)
				}
			}(cl)
		}
	}()

	return wsApp
}

/*
type WebsocketAppChecker struct {
	clients *Clients
}

func (s *WebsocketAppChecker) RequestCheck(r *engine.Request) bool {
	log.Println("CHECK", r.URL.Path)
	return r.URL.Path == "/api"
}

func NewWebsocketApplication(base engine.Engine) engine.Engine {
	app := &WebsocketAppChecker{

	}
	websocketApp := engine.NewWebsocketApplication(app, engine.DefaultUpgrader())
	go func() {
		for conn := range websocketApp.Listener() {
			.clientConnected(conn)
		}
	}()

	websocketEngine := engine.NewEngineWebsocket(
		base,
		websocketApp,
	)
	return websocketEngine
	//dapp := engine.NewEngineDomainBase(wapp, 302, "anapa-2.lan")
}
*/
