package cmd

import (
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"
)

var genpdf bool

// localbuildCmd represents the localbuild command
var localbuildCmd = &cobra.Command{
	Use:   "localbuild",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("localbuild called")
		repoPath := "src"
		binPath := "bin"
		startPort := 46000

		servicesPorts := map[string]int{}

		server := "cloud.o-forge.io"
		username := "core"

		err := deleteFolderIfExists(repoPath)
		if err != nil {
			fmt.Println("Error:", err)
		} else {
			fmt.Println("Repository deleted successfully")
		}
		//err := deleteFolderIfExists(binPath)
		if err != nil {
			fmt.Println("Error:", err)
		} else {
			fmt.Println("Binaries deleted successfully")
		}
		os.Mkdir(repoPath, 0755)
		os.Mkdir(binPath, 0755)

		repos, err := getRepositories(server, username)
		if err != nil {
			fmt.Printf("Error: %v\n", err)
			return
		}

		exclude := []string{"deprecated", "oc-lib", "oc-doc", "oc-release", "oc-deploy", "oc-local", "oc-test", "oc-tools"}

		for _, repo := range repos {
			fmt.Printf("Repository : %s\n", repo.Name)
			if isRepoValid(repo.Name, exclude) {
				processFolder(repoPath, [][]string{{"git", "clone", repo.CloneURL}})
			}
		}

		var commands [][]string
		for _, repo := range repos {
			fmt.Printf("Repository: %s\n", repo.Name)
			if !strings.Contains(repo.Name, "deprecated") && !strings.Contains(repo.Name, "oc-lib") && !strings.Contains(repo.Name, "oc-doc") {
				if fileExists(repoPath + "/" + repo.Name + "/go.mod") {
					commands = [][]string{
						{"go", "build"},
						{getMoveCommand(), getExecutableName(repo.Name), "../../bin/"},
					}
					fmt.Println("looking for config file: " + repoPath + "/" + repo.Name + "/" + repo.Name[3:] + ".json")
					if fileExists(repoPath + "/" + repo.Name + "/" + repo.Name[3:] + ".json") {
						isService, err := updatePortInJSONFile(repoPath+"/"+repo.Name+"/"+repo.Name[3:]+".json", binPath+"/"+repo.Name[3:]+".json", startPort)
						if err != nil {
							fmt.Println("Error:", err)
						}
						if isService {
							fmt.Println(repo.Name[3:] + " is a service, setting port.")
							servicesPorts[repo.Name[3:]] = startPort
							startPort += 1
						}
						if genpdf {
							commands = append(commands, []string{"swagger2pdf", "swagger/swagger.json", "../../bin/" + repo.Name[3:] + ".pdf"})
						}
					}
				} else {
					commands = [][]string{
						{"flutter", "build", "web"},
						{getMoveCommand(), "build/web", "../../bin/"},
					}
				}
				processFolder(repoPath+"/"+repo.Name, commands)
			}
		}
		writeCaddyfile(servicesPorts, binPath+"/Caddyfile")

	},
}

func init() {
	rootCmd.AddCommand(localbuildCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// localbuildCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	localbuildCmd.Flags().BoolVarP(&genpdf, "pdf", "p", false, "Generate PDFs")
}
