package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"net/http"
	"os"
	"path/filepath"

	"redisdog/model"
)

type StatRet struct {
	Errno int          `json:"errno"`
	Error string       `json:"error"`
	Data  []*RedisInfo `json:"data"`
}

type InfoRet struct {
	Errno int        `json:"errno"`
	Error string     `json:"error"`
	Data  *RedisInfo `json:"data"`
}

func index_default(resp http.ResponseWriter, req *http.Request) {
	sess, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	//视图输出
	files := []string{
		filepath.Join(Cfg.TmplDir, "index.tmpl"),
		filepath.Join(Cfg.TmplDir, "header.tmpl"),
		filepath.Join(Cfg.TmplDir, "navbar.tmpl"),
	}
	tmpl, err := template.New("index.tmpl").Funcs(TmplFuncMap).ParseFiles(files...)
	if err != nil {
		resp.WriteHeader(500)
		io.WriteString(resp, err.Error())
		return
	}
	tmpl.Execute(resp, struct {
		Sess  *Session
		Req   *http.Request
		Title string
	}{
		sess,
		req,
		"首页",
	})
}

func index_stats(resp http.ResponseWriter, req *http.Request) {
	_, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	mdlRedisCfg := model.NewRedisCfg(Db)
	rows, err := mdlRedisCfg.GetAll(0)
	if err != nil {
		ret, _ := json.Marshal(ErrorRet{Errno: 0, Error: err.Error()})
		resp.Write(ret)
		return
	}
	stats := make([]*RedisInfo, 0)
	for _, row := range rows {
		stats = append(stats, queryRedisInfo(row))
	}
	ret, _ := json.Marshal(StatRet{Errno: 0, Error: "", Data: stats})
	resp.Write(ret)
}

func index_info(resp http.ResponseWriter, req *http.Request) {
	_, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	req.ParseForm()
	idstr := req.Form.Get("id")
	if idstr == "" {
		resp.Write(ERROR_RET(1, "缺少ID字段!"))
		return
	}
	id := int(0)
	_, err := fmt.Sscanf(idstr, "%d", &id)
	if err != nil {
		resp.Write(ERROR_RET(2, "ID的值不是整数!"))
		return
	}
	if id <= 0 {
		resp.Write(ERROR_RET(3, "ID的值必须大于0!"))
		return
	}
	mdlRedisCfg := model.NewRedisCfg(Db)
	row, err := mdlRedisCfg.Get(int64(id))
	if err != nil {
		resp.Write(ERROR_RET(4, err.Error()))
	} else {
		info := queryRedisInfo(row)
		if info.Error == "" {
			ret, _ := json.Marshal(InfoRet{Errno: 0, Error: "", Data: info})
			resp.Write(ret)
		} else {
			resp.Write(ERROR_RET(5, info.Error))
		}
	}
}

func index_favicon(resp http.ResponseWriter, req *http.Request) {
	file, err := os.OpenFile(filepath.Join(Cfg.ResourcesDir, "favicon.ico"), os.O_RDONLY, 0644)
	if err != nil {
		resp.WriteHeader(404)
		return
	}
	defer file.Close()
	resp.Header().Set("Content-Type", "image/x-icon")
	data := make([]byte, 1024)
	for {
		if l, err := file.Read(data); err == io.EOF {
			break
		} else if err != nil {
			break
		} else {
			resp.Write(data[0:l])
		}
	}
}

func index_forbidden(resp http.ResponseWriter, req *http.Request) {
	sess, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	//视图输出
	files := []string{
		filepath.Join(Cfg.TmplDir, "forbidden.tmpl"),
		filepath.Join(Cfg.TmplDir, "header.tmpl"),
		filepath.Join(Cfg.TmplDir, "navbar.tmpl"),
	}
	tmpl, err := template.New("forbidden.tmpl").Funcs(TmplFuncMap).ParseFiles(files...)
	if err != nil {
		resp.WriteHeader(500)
		io.WriteString(resp, err.Error())
		return
	}
	tmpl.Execute(resp, struct {
		Sess  *Session
		Req   *http.Request
		Title string
	}{
		sess,
		req,
		"首页",
	})
}
