package util

import (
	"fmt"
	"math"

	"github.com/juju/errors"
	"github.com/pingcap/wormhole/pkg/whpb"
	"github.com/siddontang/go-mysql/mysql"
)

// Version information.
var (
	BuildTS = "None"
	GitHash = "None"
)

// PrintInfo prints the octopus version information
func PrintInfo() {
	fmt.Println("Git Commit Hash:", GitHash)
	fmt.Println("UTC Build Time: ", BuildTS)
}

//OriginError return original err
func OriginError(err error) error {
	for {
		e := errors.Cause(err)
		if e == err {
			break
		}
		err = e
	}
	return err
}

// CompareBinlogPosition compare two binlog position
func CompareBinlogPosition(s, t *whpb.Position) int {
	a := mysql.Position{
		Name: s.GetMysqlBinlogFile(),
		Pos:  uint32(s.GetMysqlBinlogPos()),
	}
	b := mysql.Position{
		Name: t.GetMysqlBinlogFile(),
		Pos:  uint32(t.GetMysqlBinlogPos()),
	}

	return CompareBinlogPosWithDeviation(a, b, 0)
}

// CompareBinlogPosWithDeviation compares binlog positions.
// The result will be 0 if |a-b| < deviation, otherwise -1 if a < b, and +1 if a > b.
func CompareBinlogPosWithDeviation(a, b mysql.Position, deviation float64) int {
	if a.Name > b.Name {
		return 1
	}
	if a.Name < b.Name {
		return -1
	}

	if math.Abs(float64(a.Pos-b.Pos)) <= deviation {
		return 0
	}

	if a.Pos < b.Pos {
		return -1
	}

	return 1
}
