package main

import (
	"encoding/json"
	"html/template"
	"fmt"
	"net/http"
	// "github.com/radovskyb/watcher"
)

func main(){
	// w := watcher.New()
	port := ":8080"
	http.HandleFunc("/{$}", HtmlContentMiddleware(HomeHandler))
	http.HandleFunc("/about", HtmlContentMiddleware(AboutHandler))
	http.HandleFunc("GET /api", HtmlContentMiddleware(ApiHandler))
	http.HandleFunc("POST /api", HtmlContentMiddleware(ApiHandler))
	http.HandleFunc("/", NotFoundHandler)

	fmt.Println("http://localhost"+port)
	http.ListenAndServe(port, nil)
}

type handleFunc func(w http.ResponseWriter, r *http.Request) 

func HtmlContentMiddleware(f handleFunc) handleFunc {
	return func(w http.ResponseWriter, r *http.Request){
		w.Header().Add("Content-Type", "text/html")
		f(w,r)
	}
}


func HomeHandler(w http.ResponseWriter, r *http.Request){

	// data := struct{
	// 	Name string
	// }{
	// 	Name: "Coja",
	// }

	temp := template.New("home")
	temp.Parse(baseTemplate)
	temp.Execute(w,messages)

	// home := "<html><body><i>Hello world</i></body></html>"
	// w.Header().Add("Content-Type", "text/html")

	w.Write(temp)
}

func AboutHandler(w http.ResponseWriter, r *http.Request){
	// w.Header().Add("Content-Type", "text/html")
	w.Write([]byte("about"))
}

func NotFoundHandler(w http.ResponseWriter, r *http.Request){
	// w.Header().Add("Content-Type", "text/html")
	w.WriteHeader(http.StatusNotFound)
	w.Write([]byte("404 Not Found"))
}

func ApiHandler(w http.ResponseWriter, r *http.Request){
	w.Header().Add("Content-Type", "application/json")
	w.WriteHeader(http.StatusNotFound)
	// w.Write([]byte("[1,2,3]"))
	var filteredMessages []Message
	userParam := r.URL.Query().Get("user")

	if userParam != ""{
		for _ ,m:=range messages {
			if userParam == m.User{
				filteredMessages = append(filteredMessages, m)
			}
		}
	} else{
			filteredMessages = messages
	}
	json.NewEncoder(w).Encode(filteredMessages)
}

func NewMessageHandler(w http.ResponseWriter, r *http.Request){

	var message Message

	err :=  json.NewDecoder(r.Body).Decode(&message)
	userParam := r.URL.Query().Get("user")

	if err != nil{
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	if userParam != ""{
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// messages.append(messages, message)
}
