// Copyright 2025 Thomas Hedeler
// Author: Thomas Hedeler
package server

import (
	"context"
	"embed"
	"io/fs"
	"ld/eventbus"
	"ld/interval"
	"ld/sqlite"
	"log"
	"net/http"
	"text/template"
)

type Server struct {
	Ctx        context.Context
	StateDB    *sqlite.Database
	Static     fs.FS
	Embedded   embed.FS
	intervalID int
	Ebus       *eventbus.EventBus
	Templ      *template.Template
	Mux        *http.ServeMux
}

func New(
	stateDB *sqlite.Database,
	embedded embed.FS,
	ebus *eventbus.EventBus,

) (*Server, error) {

	// creating the server
	return &Server{
		StateDB:  stateDB,
		Embedded: embedded,
		Ebus:     ebus,
	}, nil
}

func (s *Server) Start() error {

	// // start the task engine
	s.intervalID = interval.SetInterval(s.interval, 1000) // check for executable tasks every 1 second
	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
}
