package alarm

import (
	"fmt"
	"github.com/vrg0/go-common/logger"
	"strconv"
	"strings"
)

type Compare struct {
}

/**
	real < alter
 */
func (Compare) Less(alter string, real []string) bool {
	rs := true
	lastIndex := len(real) - 1
	for i, r := range real {
		if i != 0 || i != lastIndex {
			if r == "0" {
				continue
			}
			rs = rs && (r < alter)
		}
	}
	return rs
}

func (Compare) Greater(alter string, real []string) bool {
	rs := true
	lastIndex := len(real) - 1
	for i, r := range real {
		if i != 0 || i != lastIndex {
			rs = rs && (r > alter)
		}
	}
	return rs
}

/**
	real = alter
 */
func (Compare) Equal(alter string, real []string) bool {
	rs := true
	lastIndex := len(real) - 1
	for i, r := range real {
		if i != 0 || i != lastIndex {
			rs = rs && (r == alter)
		}
	}
	return rs
}

//限制同比
func (Compare) LimitComparedWithSame(alter string, old []string, current []string) bool {
	logger.Info(alter, old, current)
	logger.Info("old:", strings.Join(old, ","), "new: ", strings.Join(current, ","))
	rs := true
	lastIndex := len(current) - 1
	for i, r := range current {
		if i != 0 || i != lastIndex {
			rs = rs && limitCompareSame(alter, old[i], r)
		}
	}
	return rs
}

/**
	同比超过alter
 */
func (Compare) ComparedWithSame(alter string, old []string, current []string) bool {
	logger.Info("old:", strings.Join(old, ","), "new: ", strings.Join(current, ","))
	rs := true
	lastIndex := len(current) - 1
	for i, r := range current {
		if i != 0 || i != lastIndex {
			rs = rs && compareSame(alter, old[i], r)
		}
	}
	return rs

}

func limitCompareSame(alter string, old string, current string) bool {
	cf := parseToFloat(current)
	of := parseToFloat(old)
	if cf < 200 && of < 200 {
		return false
	}
	return (cf-of)/of > parseToFloat(alter)
}

func compareSame(alter string, old string, current string) bool {
	cf := parseToFloat(current)
	of := parseToFloat(old)
	if of == 0 {		//jingbo.wang, 忽略of为0的场景
		return false
	}
	return (cf-of)/of > parseToFloat(alter)
}

func parseToFloat(value string) float64 {
	rs, err := strconv.ParseFloat(value, 64)
	if nil != err {
		logger.Error(err)
	}
	return rs
}

type MsgBuilder struct {
}

func (MsgBuilder) Less(alter string) string {
	return fmt.Sprintf(" 低于阈值：%s", alter)
}

/**
	real > alter
 */
func (MsgBuilder) Greater(alter string) string {
	return fmt.Sprintf(" 高于阈值：%s", alter)
}

/**
	real = alter
 */
func (MsgBuilder) Equal(alter string) string {
	return fmt.Sprintf(" 等于阈值：%.3s", alter)
}

/**
	同比超过alter
 */
func (MsgBuilder) ComparedWithSame(alter string) string {
	return "同比超过" + alter
}


//限制同比
func (MsgBuilder) LimitComparedWithSame(alter string) string {
	return "同比超过" + alter
}