package main

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

	"redisdog/model"
)

type SysCfgMiscGetRet struct {
	Errno int               `json:"errno"`
	Error string            `json:"error"`
	Data  map[string]string `json:"data"`
}

func syscfg_misc(resp http.ResponseWriter, req *http.Request) {
	sess, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	if !sess.Account.IsSuper {
		resp.Header().Set("Location", "/index/forbidden")
		resp.WriteHeader(302)
		return
	}
	//视图输出
	files := []string{
		filepath.Join(Cfg.TmplDir, "syscfg", "misc.tmpl"),
		filepath.Join(Cfg.TmplDir, "header.tmpl"),
		filepath.Join(Cfg.TmplDir, "navbar.tmpl"),
	}
	tmpl, err := template.New("misc.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,
			"其它配置",
		})
	}
}

func syscfg_misc_get(resp http.ResponseWriter, req *http.Request) {
	sess, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	if !sess.Account.IsSuper {
		ret, _ := json.Marshal(ErrorRet{Errno: 404, Error: "Forbidden"})
		resp.Write(ret)
		return
	}
	mdl := model.NewSysCfg(Db)
	values, err := mdl.GetByKeys([]string{"monitor_loop_interval", "monitor_mail_interval", "log_kept_days"})
	if err != nil {
		resp.Write(ERROR_RET(1, err.Error()))
	} else {
		ret, _ := json.Marshal(SysCfgMiscGetRet{Errno: 0, Error: "", Data: values})
		resp.Write(ret)
	}
}

func syscfg_misc_set(resp http.ResponseWriter, req *http.Request) {
	sess, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	if !sess.Account.IsSuper {
		ret, _ := json.Marshal(ErrorRet{Errno: 404, Error: "Forbidden"})
		resp.Write(ret)
		return
	}
	req.ParseForm()
	moniotrLoopIntervalStr := req.PostForm.Get("monitor_loop_interval")
	if moniotrLoopIntervalStr == "" {
		resp.Write(ERROR_RET(1, "检查间隔不能为空"))
		return
	}
	monitorMailIntervalStr := req.PostForm.Get("monitor_mail_interval")
	if monitorMailIntervalStr == "" {
		resp.Write(ERROR_RET(2, "报警邮件发送间隔不能为空"))
		return
	}
	logKeptDaysStr := req.PostForm.Get("log_kept_days")
	if logKeptDaysStr == "" {
		resp.Write(ERROR_RET(3, "日志保留天数不能为空"))
		return
	}
	if _, err := strconv.Atoi(moniotrLoopIntervalStr); err != nil {
		resp.Write(ERROR_RET(4, "检查间隔不是有效的数字值"))
		return
	}
	if _, err := strconv.Atoi(monitorMailIntervalStr); err != nil {
		resp.Write(ERROR_RET(5, "报警邮件发送间隔不是有效的数字值"))
		return
	}
	if _, err := strconv.Atoi(logKeptDaysStr); err != nil {
		resp.Write(ERROR_RET(6, "日志保留天数不是有效的数字值"))
		return
	}
	mdl := model.NewSysCfg(Db)
	if _, err := mdl.Set("monitor_loop_interval", moniotrLoopIntervalStr); err != nil {
		resp.Write(ERROR_RET(7, "操作失败(monitor_loop_interval)"))
	}
	if _, err := mdl.Set("monitor_mail_interval", monitorMailIntervalStr); err != nil {
		resp.Write(ERROR_RET(8, "操作失败(monitor_mail_interval)"))
	}
	if _, err := mdl.Set("log_kept_days", logKeptDaysStr); err != nil {
		resp.Write(ERROR_RET(9, "操作失败(log_kept_days)"))
	}
	SYSLOG("WARN", fmt.Sprintf("管理员#%d %s %s修改了其它配置", sess.Account.Id, sess.Account.Name, sess.Account.Account))
	//更新配置缓存
	err := SysCfg.Load()
	if err != nil {
		resp.Write(ERROR_RET(7, fmt.Sprintf("配置更新成功，但未能成功刷新:%s", err.Error())))
	} else {
		resp.Write(ERROR_RET(0, ""))
	}
}
