package main

import (
	"bytes"
	"fmt"
	"io"
	"os/exec"
	"strings"

	"github.com/pingcap/schrodinger/pkg/test_client"
)

// execJq executes the jq query on the reader.
func execJq(query string, reader io.Reader) bytes.Buffer {
	cmdString := []string{"jq", "-r", query}

	cmd := exec.Command(cmdString[0], cmdString[1:]...)
	cmd.Stdin = reader
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	if err := cmd.Run(); err != nil {
		client.Errorf("[scale tikv] %s stderr: %s", strings.Join(cmdString, " "), stderr.String())
		client.Fatalf("[scale tikv] jq fail: %v", err)
	}
	return stdout
}

// extractStoreIds extracts all store ids from the reader.
func extractStoreIds(reader io.Reader) []string {
	var stdout = execJq(".stores|map(select(.store|.state_name = \"Up\"))|map(.store|.id)|.[]", reader)
	res := strings.Split(stdout.String(), "\n")
	for i := range res {
		res[i] = strings.Trim(res[i], "\n ")
	}
	return res
}

// extractStoreAddress extracts ip and port from the reader.
func extractStoreAddress(reader io.Reader) (string, string) {
	var stdout = execJq(".store|.address", reader)
	addr := strings.Split(strings.Trim(stdout.String(), " \n"), ":")
	return addr[0], addr[1]
}

// extractStoreState extracts store state from the reader.
func extractStoreState(reader io.Reader) string {
	var stdout = execJq(".store|.state_name", reader)
	res := strings.Trim(stdout.String(), "\n ")
	if res != "Up" && res != "Offline" && res != "Tombstone" {
		msg := fmt.Sprintf("Bad store state: %s", res)
		panic(msg)
	}
	return res
}
