package server

import (
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"strings"

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

func Wildcard(w http.ResponseWriter, r *http.Request, s *Server) {
	baseDir := "./templates/"
	endpoint := strings.TrimPrefix(r.URL.Path, "/")

	if action, ok := findRoute(r.URL.Path, s.Routes); ok {
		handlers := makeFuncMap()

		handler, exists := handlers[action]
		if !exists {
			resp, code := inout.ParseTemplate("templates/error.tmpl", fmt.Errorf("handler %s not found", action))
			w.Header().Set("Content-Type", "text/html")
			w.WriteHeader(code)
			w.Write(resp)
			return
		}

		handler(w, r)
		return
	}

	if endpoint == "" {
		endpoint = "index.html"
	}

	path := filepath.Join(baseDir, endpoint)
	_, err := os.Stat(path)
	if err != nil {
		w.Header().Set("Content-Type", "text/html")
		resp, code := inout.ParseTemplate("templates/error.tmpl", err)
		w.WriteHeader(code)
		w.Write(resp)
		return
	}
	w.Write(inout.FileToBytes(path))
}
func findRoute(path string, routes map[string]string) (string, bool) {
	// 1. exact match
	if action, ok := routes[path]; ok {
		return action, true
	}

	// 2. longest prefix match
	longest := ""
	action := ""

	for route, a := range routes {
		if strings.HasPrefix(path, route) {
			if len(route) > len(longest) {
				longest = route
				action = a
			}
		}
	}

	if longest != "" {
		return action, true
	}

	return "", false
}

func makeFuncMap() map[string]hfunc {
	handlers := map[string]hfunc{
		/*"VIEW_NOTE": func(w http.ResponseWriter, r *http.Request) {
			note := r.URL.Query().Get("note")
			Notes(w, r, note)
		},
		"EDIT_NOTE": func(w http.ResponseWriter, r *http.Request) {
			note := r.URL.Query().Get("note")
			EditNotes(w, r, note)
		},
		"LIST_NOTES": func(w http.ResponseWriter, r *http.Request) {
			srv := Server{}
			err := inout.FileToObj("mynotes_cfg.json", &srv)
			if err != nil {
				srv.Err = err
			}
			ListNotes(w, r, &srv)
		},*/
		"API": func(w http.ResponseWriter, r *http.Request) {
			srv := Server{}
			err := inout.FileToObj("mynotes_cfg.json", &srv)
			if err != nil {
				srv.Err = err
			}
			API(w, r, &srv)
		},
		"MKDOWN_CONVERT": MDToHTML,
		"DESIGN_VIEW": func(w http.ResponseWriter, r *http.Request) {
			note := r.URL.Query().Get("note")
			srv := Server{}
			err := inout.FileToObj("mynotes_cfg.json", &srv)
			if err != nil {
				srv.Err = err
			}
			Design_viewer(w, r, &srv, note)
		},
	}
	return handlers
}
