package handlers

import (
	"database/sql"
	"encoding/json"
	"flag"
	"net/http"
	"path/filepath"

	"github.com/golang/glog"
	"github.com/gorilla/mux"

	"xinu.tv/email/db"
)

var staticDir = flag.String("static", "static",
	"directory containing static web resources.")

type handler struct {
	c *db.Conn
}

func (h *handler) OriginalHandler(w http.ResponseWriter, r *http.Request) {
	var blob []byte
	hash := mux.Vars(r)["hash"]
	err := h.c.OriginalBlobByHash(hash, &blob)
	switch err {
	case nil:
		w.Header().Set("Content-Type", "text/plain")
		if _, err := w.Write(blob); err != nil {
			glog.Error(err)
		}
	case sql.ErrNoRows:
		http.NotFound(w, r)
	default:
		glog.Error(err)
	}
}

func decodeToken(token string, p *db.Paginator) error {
	return nil
}

func (h *handler) LabelHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	p := &db.Paginator{Label: vars["label"]}
	if p.Label == "" {
		p.Label = db.MagicAllLabel
	}
	token := vars["token"]
	if err := decodeToken(token, p); err != nil {
		glog.Error("LabelHandler: Failed to decode token %q: %v", token, err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	glog.Infoln("Listing:", p)
	res, err := h.c.Index(p)
	if err != nil {
		glog.Errorln("LabelHandler:", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	enc := json.NewEncoder(w)
	err = enc.Encode(res)
	if err != nil {
		glog.Errorln("LabelHandler:", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

func staticHandler(w http.ResponseWriter, r *http.Request) {
	fs := http.FileServer(http.Dir(*staticDir))
	if r.URL.Path == "/" {
		http.ServeFile(w, r, filepath.Join(*staticDir, "index.html"))
		return
	}
	fs.ServeHTTP(w, r)
}

func Handlers(c *db.Conn) http.Handler {
	h := &handler{c: c}

	r := mux.NewRouter()
	r.HandleFunc("/css/", staticHandler)
	r.HandleFunc("/raw/{hash}", h.OriginalHandler)
	r.HandleFunc("/l/{label}", h.LabelHandler)
	r.PathPrefix("/").HandlerFunc(staticHandler)
	return r
}
