package main

/*
Отписка от матча:
- метод Unwatch
- когда матч исчезнет из лайва
*/

import (
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gordenko.dev/dima/onexbet"
	"gordenko.dev/dima/onexbet/daemon"
	"gordenko.dev/dima/web"
	"gordenko.dev/dima/web/api"
	"gordenko.dev/dima/web/router"
	"gordenko.dev/dima/ws"
	"gordenko.dev/dima/ws/publisher"
)

const (
	port = 7772
	dsn  = "user:password@/tipper"
)

func main() {
	wsServer, err := ws.NewPublicServer(ws.PublicServerOptions{
		Logger:                log.New(os.Stdout, "ws: ", log.LstdFlags),
		LostConnectionTimeout: 1 * time.Minute,
		Ping:                  true,
	})
	if err != nil {
		log.Fatalf("ws.NewPublicServer: %s\n", err)
	}

	wsPublisher, err := publisher.NewPublicPublisher(publisher.PublicPublisherOptions{
		WsPublicServer: wsServer,
	})
	if err != nil {
		log.Fatalf("ws.NewPublicPublisher: %s\n", err)
	}

	//

	logger := log.New(os.Stdout, "", log.LstdFlags)

	d := daemon.New(daemon.Options{
		Logger: logger,
		SportIDs: []onexbet.OnexbetSport{
			onexbet.Handball,
			onexbet.Football,
			onexbet.Tennis,
		},
		WsPublisher: wsPublisher,
	})

	wsServer.OnConnected(d.OnWsClientConnected)

	publicAPI, err := api.NewAPI(api.Options{
		Logger: logger,
	})

	publicAPI.PublicFunc("watch", d.Watch)
	publicAPI.PublicFunc("unwatch", d.Unwatch)
	//publicAPI.Handle("searchMatchCandidates", s.SearchMatchCandidates)

	r := router.New()
	r.PrefixHandle("/api", publicAPI)
	r.Handle("/ws", wsServer)

	app, err := web.NewApp(web.AppOptions{
		Port:   port,
		Router: r,
	})
	if err != nil {
		log.Fatalf("web.NewApp: %s\n", err)
	}

	go app.Run()
	go d.Run()

	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

	<-sigs

	logger.Println("daemon stopped.")
}
