package commands

import (
	"fmt"
	"io"

	"text/tabwriter"

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

const Timeout = "5"

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

var startCmd = &cobra.Command{
	Use:   "start",
	Short: "Start the dev environment",
	Example: `
	localdev start
	localdev start --ingester
	localdev start -i
	localdev start --pantheon
	localdev start -i -p
	`,
	RunE: func(cmd *cobra.Command, args []string) (err error) {
		fmt.Println("Welcome to the Contiamo localdev environment")

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

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

		err = startLocaldev(cmd, withIngester, withPantheonRedir, nil)
		if err != nil {
			return err
		}

		return printStartMessage(cmd.OutOrStdout())

	},
}

func printStartMessage(w io.Writer) (err error) {
	writer := tabwriter.NewWriter(w, 0, 8, 1, '\t', tabwriter.AlignRight)
	_, _ = fmt.Fprintln(writer, "App:\thttp://localhost:9898/contiamo/profile")
	_, _ = fmt.Fprintln(writer, "Tracing:\thttp://localhost:16686/search")
	_, _ = fmt.Fprintln(writer, "Mailtrap:\thttp://localhost:8025")
	_, _ = fmt.Fprintln(writer, "Spark:\thttp://localhost:4040")
	if config.STunnelEnabled() {
		_, _ = fmt.Fprintln(writer, "stunnel:\t✅ configured for pg protocol at localhost:5435")
	} else {
		_, _ = fmt.Fprintln(writer, "stunnel:\t❌ not configured")
	}
	_, _ = fmt.Fprintln(writer, "----")
	_, _ = fmt.Fprintln(writer, "Email:\tlemon@example.com")
	_, _ = fmt.Fprintln(writer, "Password:\tlocaldev")
	return writer.Flush()
}

func serviceFlags(flags *pflag.FlagSet) {
	flags.BoolP("ingester", "i", false, "enable the ingester and related services.")
	flags.BoolP("pantheon", "p", false, "enable the redir image for local Pantheon development.")
}
