package steps

import (
	"context"
	"fmt"
	"time"

	"github.com/pkg/errors"
)

// Initial changefeed.toml
type changefeedConfig struct {
	changefeedCategory *string
	changefeedContent  *string
}

func (d changefeedConfig) String() string {
	return fmt.Sprintf("add `%s` and `%s` to changefeed.toml", *(d.changefeedCategory), *(d.changefeedContent))

}

func (d *changefeedConfig) Execute(ctx context.Context) error {
	fileName := "/tmp/changefeed.toml"
	cmd := "echo -e >" + fileName + " "
	cmd = cmd + "\"" + *d.changefeedCategory + " \n\""
	cmd = cmd + "\"" + *d.changefeedContent + " \n\""
	cdcHost, err := GetCDCHost(ctx)
	if err != nil {
		return err
	}
	o, err := cdcHost.Exec(cmd, 10*time.Second)
	if err != nil {
		return err
	}
	if o.ExitCode != 0 {
		return errors.Errorf("Changefeed config file generated failed, exitcode: +%v", o.ExitCode)
	}
	return nil
}

var _ Step = &changefeedConfig{}

func NewChangeFeedConfig(changefeedCategory *string, changefeedContent *string) Step {
	return &changefeedConfig{
		changefeedCategory: changefeedCategory,
		changefeedContent:  changefeedContent,
	}
}
