package web

import (
	"encoding/json"
	"html/template"
	"net/http"
	"strconv"
	. "tools"

	"github.com/gorilla/mux"
	"github.com/gorilla/sessions"
)

var (
	TplPath             = "./res/template/"
	Route   *mux.Router = mux.NewRouter()
	Store               = sessions.NewCookieStore([]byte("very-secret"))
)

func init() {
	Store.MaxAge(30 * 60)
}

func CheckSession(w http.ResponseWriter, r *http.Request) bool {
	session, _ := Store.Get(r, SN)
	//log.Println(session.Values["s_name"])
	if session == nil || session.Values["s_name"] == nil {
		return false
	}
	session.Save(r, w)
	return true
}

func WriteJSON(w http.ResponseWriter, data interface{}) {
	resByte, _ := json.Marshal(data)
	w.Header().Set("Content-Type", "application/json")
	w.Write(resByte)
}

func GetVal(r *http.Request) map[string]interface{} {
	val := map[string]interface{}{}
	for k, _ := range r.Form {
		if k != "_id" {
			v := r.FormValue(k)
			switch k[:2] {
			case "s_": //string型
				val[k] = v
			case "l_": //int64位
				val[k], _ = strconv.ParseInt(v, 10, 64)
			case "i_": //int型
				val[k], _ = strconv.Atoi(v)
			}
		}
	}
	return val
}

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

func ExecuteTpl(tplpath string, data interface{}, w http.ResponseWriter) {
	defer Catch()
	//*******
	//开发环境
	templates = template.Must(template.ParseGlob("./res/template/*"))
	err := templates.ExecuteTemplate(w, tplpath, data)
	CheckError(err)
}

func GetOrder(sel string) int {
	defer Catch()
	q := `{"s_name":"` + sel + `"}`
	res, _ := MgoClass.FindOneByField("rc_order", q, `{"i_order":1}`)
	v := IntAllDef((*res)["i_order"], 1)
	set := map[string]interface{}{
		"$set": map[string]interface{}{
			"s_name":  sel,
			"i_order": (v + 1),
		},
	}
	MgoClass.Update("rc_order", q, set, true, false)
	return v
}
