package main

import (
	"flag"
	"text/template"
	"net/http"
	"fmt"
	//"io"
	"log"
	"strconv"
	//"path"

	"git.sr.ht/~ark/ytparser"
)

func getLangs() []string {
	return []string{"en", "fr", "de", "ja", "ru"}
}

func getOrders() []string {
	return []string{"relevance", "date", "views", "rating"}
}

func serve(w http.ResponseWriter, templatePath string, data interface{}) {
	funcMap := template.FuncMap {
		"inc": func(i int) int {
			return i + 1
		},
		"dec": func(i int) int {
			return i - 1
		},
	}
	t, err := template.New("base.html").Funcs(funcMap).ParseFiles("templates/base.html", templatePath)
	if err != nil {
		panic(err)
	} else {
		if err := t.Execute(w, data); err != nil {
			log.Println(err)
		}
	}
}

func index(w http.ResponseWriter, r *http.Request) {
	term := ""
	page := 0
	lang := ""
	order := "relevance"
	items, err := ytparser.Search("", 0, "", "relevance")
	if err != nil {
		log.Println(err)
		data := struct {
			Error error
		}{
			err,
		}
		serve(w, "templates/error.html", data)
	} else {
		data := struct {
			Langs []string
			Orders []string
			Term string
			Order string
			Items []ytparser.Item
			Page int
			Lang string
		}{
			getLangs(),
			getOrders(),
			term,
			order,
			items,
			page,
			lang,
		}
		serve(w, "templates/search.html", data)
	}
}

func search(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		query := r.URL.Query()
		term := query.Get("term")
		sPage := query.Get("page")
		lang := query.Get("lang")
		order := query.Get("order")
		var page int
		if sPage == "" {
			page = 0
		} else {
			p, err := strconv.Atoi(sPage)
			if err != nil {
				page = 0
			} else {
				page = p
			}
		}
		log.Printf("searching: %s, page: %d, lang: %s, order: %s\n", term, page, lang, order)
		items, err := ytparser.Search(term, page, lang, order)
		if err != nil {
			log.Println(err)
			data := struct {
				Error error
			}{
				err,
			}
			serve(w, "templates/error.html", data)
		} else {
			data := struct {
				Items []ytparser.Item
				Term string
				Page int
				Lang string
				Langs []string
				Order string
				Orders []string
			}{
				items,
				term,
				page,
				lang,
				getLangs(),
				order,
				getOrders(),
			}
			serve(w, "templates/search.html", data)
		}
	default:
	}
}

func embed(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		query := r.URL.Query()
		id := query.Get("id")
		serve(w, "templates/embed.html", id)
	default:
	}
}

func favicon(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "favicon.ico")
}

func main() {
	port := flag.Int("p", 8080, "The port to bind to.")
	flag.Parse()
	fs := http.FileServer(http.Dir("static"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))
	http.HandleFunc("/favicon.ico", favicon)
	http.HandleFunc("/", index)
	http.HandleFunc("/search", search)
	http.HandleFunc("/embed", embed)

	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
}
