package command

import (
	"log"
	"net"
	"os"

	"github.com/eviltomorrow/thief/internal/client"
	"github.com/spf13/cobra"
)

const (
	KB int64 = 1024
)

var uploadCmd = &cobra.Command{
	Use:   "upload",
	Short: "Upload the file to remote server",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		if source == "" {
			log.Println("[FATAL] source is nil")
			os.Exit(1)
		}
		if target == "" {
			log.Println("[FATAL] target is nil")
			os.Exit(1)
		}
		if buffersize < KB*2 || buffersize > KB*16 {
			buffersize = KB * 2
		}

		if err := client.Upload(net.JoinHostPort(address, port), source, target, buffersize, md5); err != nil {
			log.Printf("[FATAL] upload file failre, nest error: %v\r\n", err)
			os.Exit(1)
		}
	},
}

var (
	source, target string
	md5            bool
	buffersize     int64
)

func init() {
	uploadCmd.Flags().StringVarP(&address, "address", "a", "", "host for thief server")
	uploadCmd.Flags().StringVarP(&port, "port", "p", "9091", "port for thief server")
	uploadCmd.Flags().StringVarP(&source, "source", "s", "", "source location of file/dir")
	uploadCmd.Flags().StringVarP(&target, "target", "t", "", "target location of file/dir")
	uploadCmd.Flags().BoolVarP(&md5, "md5", "", false, "check md5?")
	uploadCmd.Flags().Int64VarP(&buffersize, "buffersize", "", 2*2048, "buffer size of transport")

	uploadCmd.MarkFlagRequired("address")
	uploadCmd.MarkFlagRequired("source")
	uploadCmd.MarkFlagRequired("target")

	rootCmd.AddCommand(uploadCmd)
}
