package cmd

import (
	"io/ioutil"
	"log"

	"github.com/spf13/cobra"
	gitlab "github.com/xanzy/go-gitlab"
)

var (
	pid            string
	token          string
	url            string
	getFilePath    string
	outputfilePath string
	branch         string
)

var RawCmd = &cobra.Command{
	Use:   "raw",
	Short: "Get the content of the specified file in the repository.",
	Long:  `Get the content of the specified file in the repository and save it locally.`,
	Run: func(cmd *cobra.Command, args []string) {
		// 创建一个GitLab客户端实例
		client, err := gitlab.NewClient(token, gitlab.WithBaseURL(url))
		if err != nil {
			log.Fatal(err)
		}

		// 获取仓库中指定文件的内容
		file, _, err := client.RepositoryFiles.GetRawFile(pid, getFilePath, &gitlab.GetRawFileOptions{Ref: gitlab.String(branch)})
		if err != nil {
			log.Fatal(err)
		}

		// 将内容写入文件
		err = ioutil.WriteFile(outputfilePath, []byte(file), 0644)
		if err != nil {
			log.Fatal(err)
		}
	},
}

func init() {
	RawCmd.Flags().StringVarP(&pid, "project-id", "p", "1", "The project id.")
	RawCmd.Flags().StringVarP(&token, "token", "t", "", "The token of gitlab.")
	RawCmd.Flags().StringVarP(&url, "url", "u", "", "The url of gitlab.")
	RawCmd.Flags().StringVarP(&getFilePath, "getfile-path", "g", "", "The getfile path.")
	RawCmd.Flags().StringVarP(&outputfilePath, "outputfile-path", "o", "", "The outputfile path.")
	RawCmd.Flags().StringVarP(&branch, "branch", "b", "main", "The project branch of gitlab.")
	RawCmd.MarkFlagRequired("project-id")
	RawCmd.MarkFlagRequired("token")
	RawCmd.MarkFlagRequired("url")
	RawCmd.MarkFlagRequired("outputfile-path")
	RawCmd.MarkFlagRequired("getfile-path")
	RawCmd.MarkFlagRequired("branch")
}