package commands

import (
	"fmt"
	"os"
	"os/exec"

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

func init() {
	logsCmd.Flags().BoolP("follow", "f", false, "stream and follow the logs")
	logsCmd.Flags().UintP("tail", "t", 0, "number of lines to show from teh end of the logs for each service")
}

var logsCmd = &cobra.Command{
	Use:     "logs",
	Aliases: []string{"log"},
	Short:   "print or tail the logs from a specific services",
	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		services, err := listServices(cmd, true)
		if err != nil {
			return nil, cobra.ShellCompDirectiveError
		}
		return services, cobra.ShellCompDirectiveDefault
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		follow, err := cmd.Flags().GetBool("follow")
		if err != nil {
			return nil
		}

		tail, err := cmd.Flags().GetUint("tail")
		if err != nil {
			return nil
		}

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

		if tail > 0 {
			logsArgs = append(logsArgs, fmt.Sprintf("--tail=%d", tail))
		}

		logsArgs = append(logsArgs, args...)

		compose := exec.CommandContext(
			cmd.Context(),
			"docker-compose",
			logsArgs...,
		)
		compose.Dir = config.LocaldevRoot()
		compose.Stderr = cmd.OutOrStderr()
		compose.Stdout = cmd.OutOrStdout()
		compose.Env = os.Environ()

		return compose.Run()

	},
}
