package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"

	"redisdog/model"
	"github.com/gomodule/redigo/redis"
)

type ErrorRet struct {
	Errno int    `json:"errno"`
	Error string `json:"error"`
}

type RedisInfo struct {
	Id      int64
	Address string
	Remark  string
	Error   string
	Data    map[string]string
}

func getSession(req *http.Request) (*Session, bool) {
	var sessid string
	cookies := req.Cookies()
	if len(cookies) > 0 {
		for _, item := range cookies {
			if item.Name == "sessid" && item.Value != "" {
				sessid = item.Value
				break
			}
		}
	}
	if sessid == "" {
		return nil, false
	} else {
		return SessPoll.Get(sessid)
	}
}

func checkLogin(resp http.ResponseWriter, req *http.Request) (*Session, bool) {
	sess, ok := getSession(req)
	if !ok {
		resp.Header().Set("Location", "/login")
		resp.WriteHeader(302)
	}
	return sess, ok
}

func parseRedisInfo(info string) map[string]string {
	stats := make(map[string]string, 1024)
	lines := strings.Split(info, "\r\n")
	num := len(lines)
	for i := 0; i < num; i++ {
		line := strings.TrimSpace(lines[i])
		if line == "" || line[0] == '#' {
			continue
		}
		parts := strings.SplitN(line, ":", 2)
		if len(parts) != 2 {
			continue
		}
		stats[parts[0]] = parts[1]
	}
	return stats
}

func queryRedisInfo(item *model.RedisCfgRow) *RedisInfo {
	info := RedisInfo{
		Id:      item.Id,
		Address: item.Address,
		Remark:  item.Remark,
	}
	timeout := time.Second * time.Duration(item.MaxConnectWait)
	options := []redis.DialOption{
		redis.DialConnectTimeout(timeout),
		redis.DialReadTimeout(timeout),
		redis.DialWriteTimeout(timeout),
		redis.DialKeepAlive(time.Duration(0)),
	}
	if item.Password != "" {
		options = append(options, redis.DialPassword(item.Password))
	}
	conn, err := redis.Dial("tcp", item.Address, options...)
	if err != nil {
		info.Error = err.Error()
		return &info
	}
	defer conn.Close()
	str, err := redis.String(conn.Do("info"))
	if err == nil {
		info.Data = parseRedisInfo(str)
		config, err := redis.StringMap(conn.Do("config", "get", "save"))
		if err == nil {
			info.Data["save"] = config["save"]
		} else {
			info.Data["save"] = ""
			info.Error = err.Error()
		}
	} else {
		info.Error = err.Error()
	}
	return &info
}

func resetRedisConfig(item *model.RedisCfgRow, maxMemory int64) (bool, error) {
	timeout := time.Second * time.Duration(item.MaxConnectWait)
	options := []redis.DialOption{
		redis.DialConnectTimeout(timeout),
		redis.DialReadTimeout(timeout),
		redis.DialWriteTimeout(timeout),
		redis.DialKeepAlive(time.Duration(0)),
	}
	if item.Password != "" {
		options = append(options, redis.DialPassword(item.Password))
	}
	conn, err := redis.Dial("tcp", item.Address, options...)
	if err != nil {
		return false, err
	}
	defer conn.Close()
	ret, err := redis.String(conn.Do("config", "set", "maxmemory", fmt.Sprintf("%d", maxMemory)))
	return ret == "OK", err
}

func ERROR_RET(errno int, errmsg string) []byte {
	ret, _ := json.Marshal(ErrorRet{Errno: errno, Error: errmsg})
	return ret
}

func number2size(n float64) string {
	if n < 1024 {
		return fmt.Sprintf("%d", int(n))
	} else if n < 1024*1024 {
		return fmt.Sprintf("%.2fKB", n/1024)
	} else if n < 1024*1024*1024 {
		return fmt.Sprintf("%.2fMB", n/1024/1024)
	} else if n < 1024*1024*1024*1024 {
		return fmt.Sprintf("%.2fGB", n/1024/1024/1024)
	} else {
		return fmt.Sprintf("%.2fTB", n/1024/1024/1024/1024)
	}
}

func SYSLOG(level, msg string) {
	if SysLogger == nil {
		return
	}
	SysLogger.Add(&model.SysLogRow{
		LogLevel: level,
		LogMsg:   msg,
	})
}
