package comp_test

import (
	"strconv"
	"strings"
	"testing"

	_ "github.com/go-sql-driver/mysql"
)

func versionFromTiDB(version string) string {
	version = strings.TrimPrefix(version, "5.7.25-TiDB-v")
	index := strings.Index(version, "-")
	if index == -1 {
		return version
	}

	return version[:index]
}

func versionBranch(version string) string {
	strs := strings.Split(version, ".")
	if len(strs) != 3 {
		panic(strs)
	}
	strs[2] = "0"
	return strings.Join(strs, ".")
}

func lowerBranch(version string) string {
	strs := strings.Split(version, ".")
	if len(strs) != 3 {
		panic(strs)
	}
	strs[2] = "0"
	v, err := strconv.Atoi(strs[1])
	if err != nil {
		panic(err)
	}
	if v != 0 {
		// subbranch - 1
		v = v - 1
		strs[1] = strconv.Itoa(v)
		return strings.Join(strs, ".")
	}

	strs[1] = "0"
	v, err = strconv.Atoi(strs[0])
	if err != nil {
		panic(err)
	}
	v = v - 1
	strs[0] = strconv.Itoa(v)
	return strings.Join(strs, ".")
}

func noneTestVersionBranch(t *testing.T) {
	v := versionBranch("6.0.0")
	if v != "6.0.0" {
		t.Fatal(v)
	}

	v = versionBranch("6.1.0")
	if v != "6.1.0" {
		t.Fatal(v)
	}

	v = versionBranch("5.0.6")
	if v != "5.0.0" {
		t.Fatal(v)
	}

	v = versionBranch("4.0.16")
	if v != "4.0.0" {
		t.Fatal(v)
	}
}

func noneTestLowerBranch(t *testing.T) {
	v := lowerBranch("6.1.0")
	if v != "6.0.0" {
		t.Fatal(v)
	}

	v = lowerBranch("5.0.6")
	if v != "4.0.0" {
		t.Fatal(v)
	}

	v = lowerBranch("6.0.0")
	if v != "5.0.0" {
		t.Fatal(v)
	}
}

func noneTestVersionFromTiDB(t *testing.T) {
	v := versionFromTiDB("5.7.25-TiDB-v6.0.0")
	if v != "6.0.0" {
		t.Fatal(v)
	}

	v = versionFromTiDB("5.7.25-TiDB-v6.1.0-alpha-140-ga2b2dc0")
	if v != "6.1.0" {
		t.Fatal(v)
	}

	v = versionFromTiDB("5.7.25-TiDB-v5.4.0-20220308-2-gb1c5a67")
	if v != "5.4.0" {
		t.Fatal(v)
	}

	v = versionFromTiDB("5.7.25-TiDB-v5.0.6")
	if v != "5.0.6" {
		t.Fatal(v)
	}

	v = versionFromTiDB("5.7.25-TiDB-v4.0.16")
	if v != "4.0.16" {
		t.Fatal(v)
	}
}
