package main

import (
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"os"

	"./api"
	"github.com/julienschmidt/httprouter"
)

const sockPath = "/srv/kumori.moe/sock/meikan.sock"

var tmpl = template.Must(template.ParseGlob("templates/*.gohtml"))

func init() {
	l, _ := ioutil.ReadDir("components")
	for _, v := range l {
		c, _ := ioutil.ReadFile(`components/` + v.Name())
		tmpl, _ = tmpl.Parse(string(c))
	}
}

func main() {
	os.Remove(sockPath)
	sock, err := net.Listen("unix", sockPath)

	if err != nil {
		log.Fatalln(err)
		return
	}

	router := httprouter.New()

	router.GET("/", getIndex)
	router.GET("/anime", getAnime)
	router.GET("/reload", reload)

	router.ServeFiles("/static/*filepath", http.Dir("static/"))

	err = os.Chmod(sockPath, 0770)
	if err != nil {
		log.Fatalln(err)
	}

	log.Fatal(http.Serve(sock, router))
}

func getIndex(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	err := tmpl.ExecuteTemplate(w, "home.gohtml", nil)
	if err != nil {
		println(err)
	}
}

func getAnime(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	animeList, err := api.SearchAnime("tsukaima")
	if err != nil {
		fmt.Fprint(w, err)
		return
	}
	err = tmpl.ExecuteTemplate(w, "anime.gohtml", &animeList)
	if err != nil {
		println(err)
	}
}

func reload(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	tmpl = template.Must(template.ParseGlob("templates/*.gohtml"))
	l, _ := ioutil.ReadDir("components")
	for _, v := range l {
		c, _ := ioutil.ReadFile(`components/` + v.Name())
		tmpl, _ = tmpl.Parse(string(c))
	}
}
