package data

import (
	"database/sql"
	"errors"
	"fmt"

	"code.justin.tv/d8a/buddy/lib/config"
	"code.justin.tv/d8a/buddy/lib/store"
	"github.com/aws/aws-sdk-go/service/rds"
	"github.com/spf13/cobra"
)

var ConfigureData *ConfigureCommandData

type ConfigureCommandData struct {
	*RootCommandData
	configArgs          []string
	clusterRootInstance *rds.DBInstance
	storeDb             *sql.DB
	foundCluster        *config.Cluster
}

func (data *ConfigureCommandData) Args() []string {
	return data.configArgs
}

func (data *ConfigureCommandData) DBInstance() *rds.DBInstance {
	return data.clusterRootInstance
}

func (data *ConfigureCommandData) StoreDB() *sql.DB {
	return data.storeDb
}

func (data *ConfigureCommandData) FoundCluster() *config.Cluster {
	return data.foundCluster
}

func PopulateConfigData(command *cobra.Command, args []string) error {
	err := PopulateRootData(command, args)
	if err != nil {
		return err
	}

	if len(args) < 1 {
		err := command.Usage()
		if err == nil {
			err = &UsageError{}
		}

		return err
	}

	ConfigureData = &ConfigureCommandData{
		RootData,
		[]string{},
		nil,
		nil,
		nil,
	}

	clusterName := args[0]
	ConfigureData.configArgs = args[1:]

	rdsInstance, err := ConfigureData.LocateDataStore(false)
	if err != nil {
		return err
	}
	if rdsInstance == nil {
		return errors.New("could not locate data store")
	}
	ConfigureData.clusterRootInstance = rdsInstance

	storeDb, err := store.OpenDbConn(rdsInstance, ConfigureData.SandstormClient())
	if err != nil {
		return err
	}
	ConfigureData.storeDb = storeDb

	ConfigureData.ConfigFile().Cluster, err = store.GetClusters(storeDb)
	if err != nil {
		return err
	}

	ConfigureData.foundCluster = ConfigureData.ConfigFile().GetCluster(clusterName)
	if ConfigureData.FoundCluster() == nil {
		return fmt.Errorf("There is no cluster named %s.  Did you forget to tag your instances?", clusterName)
	}

	return nil
}

//UsageError is a simple dummy error that can be used to break out of cobra command stacks without printing a message
type UsageError struct{}

func (err *UsageError) Error() string {
	return "Incorrect command syntax."
}
