package main

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

	"redisdog/model"
)

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

func syscfg_warn(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", "warn.tmpl"),
		filepath.Join(Cfg.TmplDir, "header.tmpl"),
		filepath.Join(Cfg.TmplDir, "navbar.tmpl"),
	}
	tmpl, err := template.New("warn.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_warn_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{"smtp_host", "smtp_port", "smtp_user", "smtp_pwd", "smtp_sender"})
	if err != nil {
		ret, _ := json.Marshal(ErrorRet{Errno: 1, Error: err.Error()})
		resp.Write(ret)
	} else {
		ret, _ := json.Marshal(SysCfgWarnGetRet{Errno: 0, Error: "", Data: values})
		resp.Write(ret)
	}
}

func syscfg_warn_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()
	smtpHost := req.PostForm.Get("smtp_host")
	if smtpHost == "" {
		ret, _ := json.Marshal(ErrorRet{Errno: 1, Error: "SMTP HOST不能为空"})
		resp.Write(ret)
		return
	}
	smtpPort := req.PostForm.Get("smtp_port")
	if smtpPort == "" {
		ret, _ := json.Marshal(ErrorRet{Errno: 2, Error: "SMTP端口不能为空"})
		resp.Write(ret)
		return
	}
	smtpUser := req.PostForm.Get("smtp_user")
	if smtpUser == "" {
		ret, _ := json.Marshal(ErrorRet{Errno: 3, Error: "SMTP用户不能为空"})
		resp.Write(ret)
		return
	}
	smtpPwd := req.PostForm.Get("smtp_pwd")
	if smtpPwd == "" {
		ret, _ := json.Marshal(ErrorRet{Errno: 4, Error: "SMTP密码不能为空"})
		resp.Write(ret)
		return
	}
	smtpSender := req.PostForm.Get("smtp_sender")
	if smtpSender == "" {
		ret, _ := json.Marshal(ErrorRet{Errno: 5, Error: "SMTP署名不能为空"})
		resp.Write(ret)
		return
	}
	mdl := model.NewSysCfg(Db)
	if _, err := mdl.Set("smtp_host", smtpHost); err != nil {
		ret, _ := json.Marshal(ErrorRet{Errno: 6, Error: "操作失败(host)"})
		resp.Write(ret)
	}
	if _, err := mdl.Set("smtp_port", smtpPort); err != nil {
		ret, _ := json.Marshal(ErrorRet{Errno: 6, Error: "操作失败(port)"})
		resp.Write(ret)
	}
	if _, err := mdl.Set("smtp_user", smtpUser); err != nil {
		ret, _ := json.Marshal(ErrorRet{Errno: 6, Error: "操作失败(user)"})
		resp.Write(ret)
	}
	if _, err := mdl.Set("smtp_pwd", smtpPwd); err != nil {
		ret, _ := json.Marshal(ErrorRet{Errno: 6, Error: "操作失败(pwd)"})
		resp.Write(ret)
	}
	if _, err := mdl.Set("smtp_sender", smtpSender); err != nil {
		ret, _ := json.Marshal(ErrorRet{Errno: 6, Error: "操作失败(sender)"})
		resp.Write(ret)
	}
	SYSLOG("WARN", fmt.Sprintf("管理员#%d %s %s修改了SMTP配置", sess.Account.Id, sess.Account.Name, sess.Account.Account))
	//更新配置缓存
	err := SysCfg.Load()
	if err != nil {
		ret, _ := json.Marshal(ErrorRet{Errno: 7, Error: fmt.Sprintf("配置更新成功，但未能成功刷新:%s", err.Error())})
		resp.Write(ret)
	} else {
		ret, _ := json.Marshal(ErrorRet{Errno: 0, Error: ""})
		resp.Write(ret)
	}
}
