package main

import (
	"embed"
	"flag"
	"fmt"
	"html/template"
	"io"
	"net/http"

	_ "embed"
)

var (
	intf = flag.String("i", "localhost", "interface")
	port = flag.Uint("p", 80, "port")
)

var (
	//go:embed templates/*
	TemplateFS embed.FS

	//go:embed static/*
	StaticFS embed.FS

	Templates *template.Template
)

func main() {
	flag.Parse()

	ParseBookmarks()

	if tmpl, err := template.New("homepage").ParseFS(TemplateFS, "templates/*"); err == nil {
		Templates = tmpl
	} else {
		panic(err)
	}

	http.HandleFunc("/", handler)
	http.HandleFunc("/search", search)
	http.HandleFunc("/style.css", style)
	http.HandleFunc("/icons.ttf", icons)
	if err := http.ListenAndServe(fmt.Sprintf("%s:%d", *intf, *port), nil); err != nil {
		panic(err)
	}
}

func handler(w http.ResponseWriter, r *http.Request) {
	data := &TmplData{
		text:      GetText(r),
		Bookmarks: Bookmarks,
		Settings:  DefaultSettings,
	}

	if err := Templates.ExecuteTemplate(w, "index.html", data); err != nil {
		panic(err)
	}
}

func style(w http.ResponseWriter, r *http.Request) {
	file, err := TemplateFS.Open("templates/style.css")
	if err != nil {
		fmt.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer file.Close()

	w.Header().Add("Content-Type", "text/css")

	if err := Templates.ExecuteTemplate(w, "style.css", DefaultSettings); err != nil {
		panic(err)
	}
}

func icons(w http.ResponseWriter, r *http.Request) {
	file, err := StaticFS.Open("static/icons.ttf")
	if err != nil {
		fmt.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer file.Close()

	w.Header().Add("Content-Type", "font/ttf")

	io.Copy(w, file)
}

func search(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	query := r.Form.Get("query")
	w.Header().Add("Location", fmt.Sprintf("https://duckduckgo.com/?q=%s", query))
	w.WriteHeader(http.StatusMovedPermanently)
}
