package main

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

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

var docPath string
var dlsrv string
var debug bool

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{}) {
	tmplPath := path.Join(docPath, templatePath)
	basePath := path.Join(docPath, "templates/base.html")
	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(basePath, tmplPath)
	if err != nil {
		panic(err)
	} else {
		if err := t.Execute(w, data); err != nil {
			log.Println(err)
		}
	}
}

func stream(w http.ResponseWriter, r *http.Request) {
	values := r.URL.Query()
	if !values.Has("url") {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	out, err := exec.Command("yt-dlp", "--print", "url", "-f", "22,18", values.Get("url")).Output()
	if err != nil {
		log.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	sout := string(out)
	data := struct {
		Url string
	}{
		strings.Trim(sout, "\n"),
	}
	serve(w, "templates/syncstream.html", data)
}

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
			Dlsrv string
		}{
			getLangs(),
			getOrders(),
			term,
			order,
			items,
			page,
			lang,
			dlsrv,
		}
		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
			}
		}
		if debug {
			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
				Dlsrv string
			}{
				items,
				term,
				page,
				lang,
				getLangs(),
				order,
				getOrders(),
				dlsrv,
			}
			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")
		url := query.Get("url")
		data := struct {
			Id string
			Url string
			Dlsrv string
		}{
			id,
			url,
			dlsrv,
		}
		serve(w, "templates/embed.html", data)
	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.")
	dir := flag.String("d", "", "Location of the templates and static resources.")
	dl := flag.String("dlsrv", "", "Link to a download server.")
	debugFlag := flag.Bool("debug", false, "Activate debug logs")
	flag.Parse()
	docPath = *dir
	dlsrv = *dl
	debug = *debugFlag
	fs := http.FileServer(http.Dir("static"))
	http.Handle("/static/", http.StripPrefix(path.Join(docPath, "/static/"), fs))
	http.HandleFunc("/favicon.ico", favicon)
	http.HandleFunc("/", index)
	http.HandleFunc("/search", search)
	http.HandleFunc("/embed", embed)
	http.HandleFunc("/stream", stream)

	log.Printf("Listening on port %d\n", *port)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
}
