package main

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

	"redisdog/model"
)

type SyscfgRedisListRet struct {
	Errno int                  `json:"errno"`
	Error string               `json:"error"`
	Data  []*model.RedisCfgRow `json:"data"`
}

type SyscfgRedisGetRet struct {
	Errno int                `json:"errno"`
	Error string             `json:"error"`
	Data  *model.RedisCfgRow `json:"data"`
}

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

func syscfg_redis(resp http.ResponseWriter, req *http.Request) {
	sess, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	//视图输出
	files := []string{
		filepath.Join(Cfg.TmplDir, "syscfg", "redis.tmpl"),
		filepath.Join(Cfg.TmplDir, "header.tmpl"),
		filepath.Join(Cfg.TmplDir, "navbar.tmpl"),
	}
	tmpl, err := template.New("redis.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 syscfg_redis_list(resp http.ResponseWriter, req *http.Request) {
	_, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	req.ParseForm()
	mdlRedisCfg := model.NewRedisCfg(Db)
	rows, err := mdlRedisCfg.GetAll(-1)
	if err != nil {
		resp.Write(ERROR_RET(1, err.Error()))
	} else {
		ret, _ := json.Marshal(SyscfgRedisListRet{Errno: 0, Error: "", Data: rows})
		resp.Write(ret)
	}
}

func syscfg_redis_get(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, err := strconv.Atoi(idStr)
	if err != nil {
		resp.Write(ERROR_RET(2, err.Error()))
		return
	}
	mdlRedisCfg := model.NewRedisCfg(Db)
	item, err := mdlRedisCfg.Get(int64(id))
	if err != nil {
		resp.Write(ERROR_RET(3, err.Error()))
	} else {
		ret, _ := json.Marshal(SyscfgRedisGetRet{Errno: 0, Error: "", Data: item})
		resp.Write(ret)
	}
}

func syscfg_redis_set(resp http.ResponseWriter, req *http.Request) {
	_, ok := checkLogin(resp, req)
	if !ok {
		return
	}
	req.ParseForm()
	Id := req.PostForm.Get("Id")
	Address := req.PostForm.Get("Address")
	Remark := req.PostForm.Get("Remark")
	Password := req.PostForm.Get("Password")
	MaxConnectWait := req.PostForm.Get("MaxConnectWait")
	MaxStatusFailed := req.PostForm.Get("MaxStatusFailed")
	MinMemoryFree := req.PostForm.Get("MinMemoryFree")
	StepMemoryIncrease := req.PostForm.Get("StepMemoryIncrease")
	MaxMemoryUsage := req.PostForm.Get("MaxMemoryUsage")
	MaxConnection := req.PostForm.Get("MaxConnection")
	MaxEviIncreased := req.PostForm.Get("MaxEviIncreased")
	MaxQPS := req.PostForm.Get("MaxQPS")
	MailList := req.PostForm.Get("MailList")
	Disabled := req.PostForm.Get("Disabled")
	if Address == "" {
		resp.Write(ERROR_RET(1, "Redis服务地址不能为空！"))
		return
	}
	if Remark == "" {
		resp.Write(ERROR_RET(2, "Redis备注名称不能为空！"))
		return
	}
	if MaxConnectWait == "" {
		resp.Write(ERROR_RET(3, "连接超时时长不能为空！"))
		return
	}
	if MaxStatusFailed == "" {
		resp.Write(ERROR_RET(4, "最大状态检测失败次数不能为空！"))
		return
	}
	if MinMemoryFree == "" {
		resp.Write(ERROR_RET(5, "最小可用内存空间不能为空！"))
		return
	}
	if StepMemoryIncrease == "" {
		resp.Write(ERROR_RET(6, "单次扩容大小不能为空！"))
		return
	}
	if MaxMemoryUsage == "" {
		resp.Write(ERROR_RET(7, "最大可用内存空间不能为空！"))
		return
	}
	if MaxConnection == "" {
		resp.Write(ERROR_RET(8, "最大并发连接数不能为空！"))
		return
	}
	if MaxEviIncreased == "" {
		resp.Write(ERROR_RET(9, "最大新增淘汰记录数不能为空！"))
		return
	}
	if MaxQPS == "" {
		resp.Write(ERROR_RET(10, "最大QPS值不能为空！"))
		return
	}
	if MailList == "" {
		resp.Write(ERROR_RET(11, "报警邮件接收邮箱列表不能为空！"))
		return
	}
	if Disabled == "" {
		resp.Write(ERROR_RET(12, "状态不能为空！"))
		return
	}
	IdInt, err := strconv.Atoi(Id)
	if err != nil {
		IdInt = 0
	}
	MaxConnectWaitInt, err := strconv.Atoi(MaxConnectWait)
	if err != nil {
		resp.Write(ERROR_RET(13, err.Error()))
		return
	}
	MaxStatusFailedInt, err := strconv.Atoi(MaxStatusFailed)
	if err != nil {
		resp.Write(ERROR_RET(14, err.Error()))
		return
	}
	MinMemoryFreeInt, err := strconv.Atoi(MinMemoryFree)
	if err != nil {
		resp.Write(ERROR_RET(15, err.Error()))
		return
	}
	StepMemoryIncreaseInt, err := strconv.Atoi(StepMemoryIncrease)
	if err != nil {
		resp.Write(ERROR_RET(16, err.Error()))
		return
	}
	MaxMemoryUsageInt, err := strconv.Atoi(MaxMemoryUsage)
	if err != nil {
		resp.Write(ERROR_RET(17, err.Error()))
		return
	}
	MaxConnectionInt, err := strconv.Atoi(MaxConnection)
	if err != nil {
		resp.Write(ERROR_RET(18, err.Error()))
		return
	}
	MaxEviIncreasedInt, err := strconv.Atoi(MaxEviIncreased)
	if err != nil {
		resp.Write(ERROR_RET(19, err.Error()))
		return
	}
	MaxQPSInt, err := strconv.Atoi(MaxQPS)
	if err != nil {
		resp.Write(ERROR_RET(20, err.Error()))
		return
	}
	DisabledInt, err := strconv.Atoi(Disabled)
	if err != nil {
		resp.Write(ERROR_RET(21, err.Error()))
		return
	}
	newRow := model.RedisCfgRow{
		Id:                 int64(IdInt),
		Address:            Address,
		Remark:             Remark,
		Password:           Password,
		MaxConnectWait:     int64(MaxConnectWaitInt),
		MaxStatusFailed:    int64(MaxStatusFailedInt),
		MinMemoryFree:      int64(MinMemoryFreeInt),
		StepMemoryIncrease: int64(StepMemoryIncreaseInt),
		MaxMemoryUsage:     int64(MaxMemoryUsageInt),
		MaxConnection:      int64(MaxConnectionInt),
		MaxEviIncreased:    int64(MaxEviIncreasedInt),
		MaxQPS:             int64(MaxQPSInt),
		MailList:           MailList,
		Disabled:           DisabledInt != 0,
	}
	mdlRedisCfg := model.NewRedisCfg(Db)
	if IdInt > 0 {
		affected, err := mdlRedisCfg.Update(&newRow)
		if err != nil {
			resp.Write(ERROR_RET(22, err.Error()))
		} else if affected > 0 {
			resp.Write(ERROR_RET(0, ""))
		} else {
			resp.Write(ERROR_RET(23, "更新失败！"))
		}
	} else {
		newRowId, err := mdlRedisCfg.Insert(&newRow)
		if err != nil {
			ret, _ := json.Marshal(ErrorRet{Errno: 22, Error: err.Error()})
			resp.Write(ret)
			resp.Write(ERROR_RET(22, err.Error()))
		} else if newRowId > 0 {
			ret, _ := json.Marshal(SyscfgRedisAddRet{Errno: 0, Error: "", Data: newRowId})
			resp.Write(ret)
		} else {
			resp.Write(ERROR_RET(23, "新增失败！"))
		}
	}
}

func syscfg_redis_del(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, err := strconv.Atoi(idStr)
	if err != nil {
		resp.Write(ERROR_RET(2, err.Error()))
		return
	}
	mdlRedisCfg := model.NewRedisCfg(Db)
	affected, err := mdlRedisCfg.Delete(int64(id))
	if err != nil {
		resp.Write(ERROR_RET(3, err.Error()))
	} else if affected > 0 {
		resp.Write(ERROR_RET(0, ""))
	} else {
		resp.Write(ERROR_RET(4, "操作失败！"))
	}
}
