package main

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

	"redisdog/model"
)

type LogMonitorLogListRetData struct {
	Count int64
	List  []*model.MonitorLogRow
}

type LogMonitorLogListRet struct {
	Errno int                      `json:"errno"`
	Error string                   `json:"error"`
	Data  LogMonitorLogListRetData `json:"data"`
}

func log_monitor(resp http.ResponseWriter, req *http.Request) {
	sess, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	//视图输出
	files := []string{
		filepath.Join(Cfg.TmplDir, "log", "monitor.tmpl"),
		filepath.Join(Cfg.TmplDir, "header.tmpl"),
		filepath.Join(Cfg.TmplDir, "navbar.tmpl"),
	}
	tmpl, err := template.New("monitor.tmpl").Funcs(TmplFuncMap).ParseFiles(files...)
	if err != nil {
		io.WriteString(resp, fmt.Sprintf("Error: %s\n", err.Error()))
	} else {
		tmpl.Execute(resp, struct {
			Sess  *Session
			Req   *http.Request
			Title string
		}{
			sess,
			req,
			"Redis监控日志",
		})
	}
}

func log_monitor_list(resp http.ResponseWriter, req *http.Request) {
	_, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	req.ParseForm()
	redisId, size, page, desc := 0, 50, 1, true
	if redisIdStr := req.Form.Get("redis_id"); redisIdStr != "" {
		if redisId, _ = strconv.Atoi(redisIdStr); redisId < 1 {
			redisId = 0
		}
	}
	if sizeStr := req.Form.Get("size"); sizeStr != "" {
		if size, _ = strconv.Atoi(sizeStr); size <= 1 {
			size = 50
		}
	}
	if pageStr := req.Form.Get("page"); pageStr != "" {
		if page, _ = strconv.Atoi(pageStr); page < 1 {
			page = 1
		}
	}
	if orderStr := req.Form.Get("order"); orderStr != "" {
		if orderStr == "ASC" {
			desc = false
		}
	}
	mdl := model.NewMonitorLog(Db)
	cnt, err := mdl.Count(int64(redisId))
	if err != nil {
		resp.Write(ERROR_RET(1, fmt.Sprintf("查询失败:%s", err.Error())))
	} else {
		logs, err := mdl.GetList(int64(redisId), int64(size*(page-1)), int64(size), desc)
		if err != nil {
			resp.Write(ERROR_RET(1, fmt.Sprintf("查询失败:%s", err.Error())))
		} else {
			ret, _ := json.Marshal(LogMonitorLogListRet{Errno: 0, Error: "", Data: LogMonitorLogListRetData{Count: cnt, List: logs}})
			resp.Write(ret)
		}
	}
}
