package utils

import (
	"fmt"
	"io/ioutil"
	"log"

	"code.justin.tv/d8a/buddy/cmd/buddy-cli/data"
	"code.justin.tv/d8a/buddy/cmd/buddy-cli/setup"
	"code.justin.tv/d8a/buddy/lib/config"
	"github.com/naoina/toml"
	"github.com/spf13/cobra"
)

var ()

var bulkCmd = &cobra.Command{
	Use:   "bulk stop|start",
	Short: "Stop or start bulk operations",
	Long:  "Stop or start bulk operations",
	RunE: func(command *cobra.Command, args []string) error {

		if len(args) < 1 {
			return command.Usage()
		}

		action := args[0]

		path := config.FindConfigFile()

		if path == "" {
			log.Fatalln("Could not locate `buddy.cfg` in the local directory or /etc/buddy.")
		}

		configFile := data.RootData.ConfigFile()

		switch action {
		case "stop":
			fmt.Printf("StopBulkOps flag was %t. Now bulk ops is stopped.\n", configFile.StopBulkOps)
			configFile.StopBulkOps = true
		case "start":
			fmt.Printf("StopBulkOps flag was %t. Now bulk ops is allowed.\n", configFile.StopBulkOps)
			configFile.StopBulkOps = false
		default:
			fmt.Printf("StopBulkOps flag was %t. Your input is not a valid command and bulk ops is not changed.\n", configFile.StopBulkOps)
			return nil
		}

		output, _ := toml.Marshal(&configFile)

		err := ioutil.WriteFile(path, []byte(output), 0644)

		if err != nil {
			return err
		}

		fmt.Println("Buddy config file is changed. Please restart the service to pick up the change.")

		return nil
	},
}

func init() {
	setup.RootCmd.AddCommand(bulkCmd)
}
