package util

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

	"github.com/juju/errors"
	"github.com/pingcap/schrodinger/pkg/test_client"
	"github.com/pingcap/schrodinger/util"
)

// GetDDLOwner gets ddl owner
func GetDDLOwner(tidbIPs []string) (string, error) {
	for _, ip := range tidbIPs {
		isOwner, err := IsDDLOwner(ip)
		if err != nil {
			return "", errors.Trace(err)
		}
		if isOwner {
			return ip, nil
		}
	}
	return "", errors.NotFoundf("ddl owner")
}

// IsDDLOwner check if ip is ddl owner
func IsDDLOwner(ip string) (bool, error) {
	resp, err := util.DoGet(http.DefaultClient, fmt.Sprintf("http://%s:10080/info", ip))
	if err != nil {
		client.Errorf("get %s error %+v", fmt.Sprintf("http://%s:10080/info", ip), err)
		return false, nil
	}
	s := make(map[string]interface{})
	err = json.Unmarshal(resp, &s)
	if err != nil {
		client.Errorf("unmarshal error %+v", err)
		return false, nil
	}
	return s["is_owner"].(bool), nil
}

// OpenGeneralLog opens general log
func OpenGeneralLog(ip string) error {
	dbDSN := fmt.Sprintf("root:@tcp(%s:4000)/test", ip)
	db, err := OpenDB(dbDSN, 20)
	if err != nil {
		return errors.Trace(err)
	}
	MustExec(db, "set @@tidb_general_log=1;")
	return nil
}
