package repl

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/jedib0t/go-pretty/v6/table"
	"github.com/spf13/cobra"
	clitypes "gitlink.org.cn/cloudream/jcs-pub/client/types"
)

func init() {
	var usePkgID *bool
	cmd := &cobra.Command{
		Use:   "lsp",
		Short: "List package information",
		Args:  cobra.ExactArgs(1),
		Run: func(cmd *cobra.Command, args []string) {
			cmdCtx := GetCmdCtx(cmd)

			if usePkgID != nil && *usePkgID {
				id, err := strconv.ParseInt(args[0], 10, 64)
				if err != nil {
					fmt.Printf("Invalid package id: %s\n", args[0])
					return
				}

				lspOneByID(cmdCtx, clitypes.PackageID(id))
			} else {
				lspByPath(cmdCtx, args[0])
			}
		},
	}
	usePkgID = cmd.Flags().BoolP("id", "i", false, "List with package id instead of path")

	RootCmd.AddCommand(cmd)
}

func lspByPath(cmdCtx *CommandContext, path string) {
	db2 := cmdCtx.repl.db

	comps := strings.Split(strings.Trim(path, clitypes.ObjectPathSeparator), clitypes.ObjectPathSeparator)
	if len(comps) != 2 {
		fmt.Printf("Package path must be in format of <bucket>/<package>")
		return
	}

	pkg, err := db2.Package().GetByFullName(db2.DefCtx(), comps[0], comps[1])
	if err != nil {
		fmt.Println(err)
		return
	}

	wr := table.NewWriter()
	wr.AppendHeader(table.Row{"ID", "Name"})
	wr.AppendRow(table.Row{pkg.PackageID, pkg.Name})
	fmt.Println(wr.Render())
}

func lspOneByID(cmdCtx *CommandContext, id clitypes.PackageID) {
	db2 := cmdCtx.repl.db

	pkg, err := db2.Package().GetByID(db2.DefCtx(), id)
	if err != nil {
		fmt.Println(err)
		return
	}

	wr := table.NewWriter()
	wr.AppendHeader(table.Row{"ID", "Name"})
	wr.AppendRow(table.Row{pkg.PackageID, pkg.Name})
	fmt.Println(wr.Render())
}
