package commands

import (
	"os"
	"os/exec"

	"github.com/contiamo/dev/cli/config"
	"github.com/spf13/cobra"
)

func init() {
	serviceFlags(restartCmd.Flags())
}

var restartCmd = &cobra.Command{
	Use:   "restart",
	Short: "restart a single service or the whole dev environment",
	Example: `
localdev restart
localdev restart hub
localdev restart hub ui`,
	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		services, err := listServices(cmd, false)
		if err != nil {
			return nil, cobra.ShellCompDirectiveError | cobra.ShellCompDirectiveNoFileComp
		}

		return services, cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp
	},
	RunE: func(cmd *cobra.Command, args []string) (err error) {

		withIngester, err := cmd.Flags().GetBool("ingester")
		if err != nil {
			return err
		}

		withPantheonRedir, err := cmd.Flags().GetBool("pantheon")
		if err != nil {
			return err
		}
		env := os.Environ()
		if withPantheonRedir {
			env = append(env, "PANTHEON_IMAGE="+config.PantheonRedirImage())
		}

		composeFiles := []string{"-f", "docker-compose.yml"}
		if withIngester {
			composeFiles = append(composeFiles, "-f", "docker-compose-extra.yml")
		}

		stopArgs := append(composeFiles, "stop")
		stopArgs = append(stopArgs, args...)

		stop := exec.CommandContext(
			cmd.Context(),
			"docker-compose",
			stopArgs...,
		)
		stop.Dir = config.LocaldevRoot()
		stop.Stderr = cmd.OutOrStderr()
		stop.Stdout = cmd.OutOrStdout()
		stop.Env = env

		err = stop.Run()
		if err != nil {
			return err
		}

		startArgs := append(composeFiles, "up", "-d")
		startArgs = append(startArgs, args...)

		start := exec.CommandContext(
			cmd.Context(),
			"docker-compose",
			startArgs...,
		)
		start.Dir = config.LocaldevRoot()
		start.Stderr = cmd.OutOrStderr()
		start.Stdout = cmd.OutOrStdout()
		start.Env = env

		err = start.Run()
		if err != nil {
			return err
		}

		return printStartMessage(cmd.OutOrStdout())
	},
}
