package main

import (
	"bufio"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"sparrow/pkg/models"
	"sparrow/pkg/productconfig"
	"sparrow/pkg/rpcs"
	"strings"

	"sparrow/pkg/server"
)

func addProduct() error {
	args := models.Product{}

	reader := bufio.NewReader(os.Stdin)

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

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

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

	fmt.Printf("product config json file: ")
	file, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	jsonfile := strings.TrimSpace(file)
	fi, err := os.Open(jsonfile)
	if err != nil {
		return err
	}
	content, err := ioutil.ReadAll(fi)
	config := string(content)
	fi.Close()
	_, err = productconfig.New(config)
	if err != nil {
		return err
	}
	args.ProductConfig = config

	reply := &models.Product{}

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

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

	return nil
}

func DoProductCommand(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 'product add'")
		}
		err := addProduct()
		if err != nil {
			return err
		}
	default:
		return errors.New("operation not suported:" + op)
	}

	return nil
}
