// Copyright 2024 codeM GmbH
// Author: Thomas Hedeler
package server

import (
	"embed"
	"ld/eventbus"
	"ld/interval"
	"ld/sqlite"
	"log"
)

type Server struct {
	SQLiteVersion string
	ServerInfo    map[string]any
	StateDB       *sqlite.Database
	Embedded      embed.FS
	LogFileName   string
	TokenDuration int // TODO einbauen
	Secret        []byte
	Header        string
	intervalID    int
	Ebus          *eventbus.EventBus
	Tasks         map[string]TaskFunc
}

func New(
	logfilename string,
	StateDB *sqlite.Database,
	embedded embed.FS,

) (*Server, error) {

	// creating the server
	return &Server{
		LogFileName: logfilename,
		StateDB:     StateDB,
		Embedded:    embedded,
		Tasks:       make(map[string]func(s *Server) error),
	}, nil
}

func (s *Server) Start() error {

	// query, err := s.Embedded.ReadFile("embed/win/server_info.sql")
	// if err != nil {
	// 	return err
	// }

	// res, err := s.StundenDB.ReadRecords(string(query))
	// if err != nil {
	// 	return err
	// }

	// s.ServerInfo = res[0]

	// err = inits.LoadLogins(s.StundenDB, s.StateDB)
	// if err != nil {
	// 	return err
	// }

	// err = inits.LoadTasks(s.StundenDB, s.StateDB)
	// if err != nil {
	// 	return err
	// }

	// // start the task engine
	// if s.Production {
	// 	s.intervalID = interval.SetInterval(s.interval, 60000) // check for executable tasks every 60 seconds
	// } else {
	// 	s.intervalID = interval.SetInterval(s.interval, 30000) // check for executable tasks every 30 seconds
	// }
	return nil
}

func (s *Server) Close() error {

	// stop the task engine
	err := interval.ClearInterval(s.intervalID)
	if err != nil {
		log.Print(err)
	}

	err = s.StateDB.Close()
	if err != nil {
		log.Print(err)
	}
	return err
}

// func to dispatch routes to all parts of the application:
// they receive references to the server and the current fiber context via closures
// this way all functions have access to server properties and can handle the
// incoming requests themselves.

// type HandlerFunc = func(s *Server, c *fiber.Ctx) error

// func (s *Server) Handler(handler HandlerFunc) func(c *fiber.Ctx) error {
// 	return func(c *fiber.Ctx) error {
// 		return handler(s, c)
// 	}
// }

// signature for internal tasks
type TaskFunc = func(s *Server) error
