package main

import (
	"fmt"

	"encoding/json"

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

func setUpImporter(cli *client.Client) (*types.APPConfig, error) {
	actions, err := cli.UploadCfgWithInfo([]byte(importerCfg), "/tikv-importer.toml")
	if err != nil {
		return nil, errors.Trace(err)
	}

	app := &types.APPConfig{
		URL:        "https://download.pingcap.org/tidb-lightning-latest-linux-amd64.tar.gz",
		BinaryName: "tikv-importer",
		Name:       "tikv-importer",
		Args:       "-C /tikv-importer.toml",
		Envs:       nil,
		Actions:    actions,
		ResourceRequirement: &types.ResourceRequirement{
			CPU:    "16",
			Memory: "16Gi",
		},
	}

	config, err := cli.CreateToolV2(app)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return config, nil
}

func setUpLightning(cli *client.Client, importerIP, tidbIP, pdIP string) (*types.APPConfig, error) {
	cfg := fmt.Sprintf(lightningCfg, importerIP, tidbIP, pdIP)
	actions, err := cli.UploadCfgWithInfo([]byte(cfg), "/tidb-lightning.toml")

	if err != nil {
		return nil, errors.Trace(err)
	}

	genSQLActions, err := cli.UploadCfgWithInfo([]byte(genDataSQL), "/sysbench.sql")
	if err != nil {
		return nil, errors.Trace(err)
	}

	actions = append(actions, genSQLActions...)

	genShellDataActions, err := cli.UploadCfgWithInfo([]byte(genDataShell), "/load.sh")
	if err != nil {
		return nil, errors.Trace(err)
	}

	actions = append(actions, genShellDataActions...)

	execCommand := &types.ExecConfig{
		Command: "sh +x /load.sh",
	}

	data, err := json.Marshal(execCommand)
	if err != nil {
		return nil, errors.Trace(err)
	}

	execAction := types.Action{
		Type: types.ActionExecuteCmd,
		Data: data,
	}
	actions = append(actions, execAction)

	app := &types.APPConfig{
		URL:        "https://download.pingcap.org/tidb-lightning-latest-linux-amd64.tar.gz",
		BinaryName: "tidb-lightning",
		Name:       "tidb-lightning",
		Args:       "-c /tidb-lightning.toml",
		Image:      "127.0.0.1:5001/pingcap/lightningagent:latest",
		Envs:       nil,
		Actions:    actions,
		ResourceRequirement: &types.ResourceRequirement{
			CPU:    "16",
			Memory: "16Gi",
		},
	}

	config, err := cli.CreateToolV2(app)
	if err != nil {
		return nil, errors.Trace(err)
	}
	_, err = setUpPrometheus(cli, config.Host, 10089)
	if err != nil {
		client.Errorf("set up prometheus failed %+v", err)
	}
	return config, nil
}

func setUpPrometheus(cli *client.Client, lightningIP string, listenPort int) (*types.APPConfig, error) {
	app := &types.APPConfig{
		Type:    types.PromeType,
		Name:    "prometheus",
		Version: "v2.0.0",
		Port:    9090,
		Args:    fmt.Sprintf("%s:%d", lightningIP, listenPort),
		Envs:    nil,
	}

	config, err := cli.CreateToolV2(app)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return config, nil
}
