package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"sparrow/pkg/models"
	"sparrow/pkg/rpcs"
	"sparrow/pkg/server"
	"strings"
)

func addVendor() error {
	args := models.Vendor{}

	reader := bufio.NewReader(os.Stdin)

	fmt.Printf("vendor name: ")
	name, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.VendorName = strings.TrimSpace(name)

	fmt.Printf("vendor description: ")
	desc, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.VendorDescription = strings.TrimSpace(desc)

	reply := &models.Vendor{}

	err = server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.SaveVendor", &args, reply)
	if err != nil {
		return err
	}

	fmt.Println("=======> vendor created successfully:")
	printStruct(reply)
	fmt.Println("=======")

	return nil
}

func DoVendorCommand(args []string) error {
	if len(args) < 1 {
		return errors.New("command arguments not enough!")
	}

	op := strings.TrimSpace(args[0])
	switch op {
	case "add":
		if len(args) > 1 {
			return errors.New("unnecessary command arguments. just type 'vendor add'")
		}
		err := addVendor()
		if err != nil {
			return err
		}
	default:
		return errors.New("operation not suported:" + op)
	}

	return nil
}
