package server

import (
	"fmt"
	"net/http"

	"git.linuxit.ro/turos.robert/mynotes/lib/inout"
)

func NewServer(filename string) *Server {
	srv := Server{}
	err := inout.FileToObj(filename, &srv)
	if err != nil {
		srv.Err = err
	}

	return &srv

}

func (s *Server) Run() {
	fmt.Println(s.Port, s.Host)
	// adding endpoints to the server
	http.HandleFunc("/", Wildcard)
	http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
		API(w, r, s)
	})
	http.HandleFunc("/notes/", func(w http.ResponseWriter, r *http.Request) {
		note := r.URL.Query().Get("note")
		Notes(w, r, note)
	})
	http.HandleFunc("/list_notes/", func(w http.ResponseWriter, r *http.Request) {
		ListNotes(w, r, s)

	})
	http.HandleFunc("/edit/", func(w http.ResponseWriter, r *http.Request) {
		note := r.URL.Query().Get("note")
		EditNotes(w, r, note)
	})

	//running server
	fmt.Printf("Server running at http://%s:%s/\n", s.Host, s.Port)
	err := http.ListenAndServe(fmt.Sprintf("%s:%s", s.Host, s.Port), nil)
	if err != nil {
		fmt.Printf("Error starting server: %+v\n", err)
	}
}
