package cmdEnv

import (
	"fmt"
	"kode-starter/config"
	"kode-starter/utils"
	"os"
	"strconv"
	"strings"

	"github.com/gookit/color"
	"github.com/spf13/cobra"
)

var EnvCmd = &cobra.Command{
	Use:   "env",
	Short: "manage environment variables",
	Long:  `A simple CLI option to manage environment variables`,
	Run: func(cmd *cobra.Command, args []string) {

		config.SetInformations(cmd, args)
		startEnvVar(cmd, args)

		// listFlag := config.GetEnvVariablesListFlag()

		// fmt.Println("listFlag: " + strconv.FormatBool(listFlag))

		// fmt.Println("GetEnvVariablesListFlag: " + strconv.FormatBool(config.GetEnvVariablesListFlag()))

		// if listFlag {
		// 	printEnvVariables()
		// }

		// err := listEnvVariables()
		// if err != nil {
		// 	fmt.Println("Error:", err)
		// 	return
		// }

		// if config.GetEnvVariablesFilterFlag() {
		// 	printEnvVariablesFilter(config.GetEnvVariablesFilter())
		// } else if config.GetEnvVariablesListFlag() {
		// 	printEnvVariables()
		// }
	},
}

func startEnvVar(cmd *cobra.Command, args []string) {

	config.SetInformations(cmd, args)
	flag := config.EnvVariablesFlag

	// if list flag is set to true list all environment variables
	fmt.Println("GetEnvVariablesListFlag: " + strconv.FormatBool(config.GetEnvVariablesListFlag()))
	if flag {
		printEnvVariables()
	}

}

func listEnvVariables() error {

	if config.GetEnvVariablesListFlag() {
		fmt.Println("GetEnvVariablesListFlag: " + strconv.FormatBool(config.GetEnvVariablesListFlag()))
		printEnvVariables()
	}

	return nil

}

func printEnvVariables() {
	fmt.Println("Environment variables")
	fmt.Println("---------------------")

	// loop over all environment variables
	for _, e := range os.Environ() {
		// split key and value
		pair := strings.Split(e, "=")
		fmt.Printf("%s=%s\n", pair[0], pair[1])
	}
}

func printEnvVariablesFilter(filter string) {
	fmt.Println("Environment variables")
	// fmt.Println("---------------------")
	utils.CreateLine(5)

	// loop over all environment variables
	for _, e := range os.Environ() {
		// split key and value
		pair := strings.Split(e, "=")
		if strings.Contains(pair[0], filter) {
			fmt.Printf("%s=%s\n", utils.ColorizeSubStrRed(pair[0], filter), color.Green.Sprint(pair[1]))
		} else if strings.Contains(pair[1], filter) {
			fmt.Printf("%s=%s\n", color.Green.Sprint(pair[0]), utils.ColorizeSubStrRed(pair[1], filter))
		} else {
			fmt.Printf("%s=%s\n", pair[0], pair[1])
		}

	}
}
