package main

import (
	"bufio"
	"errors"
	"fmt"
	"sparrow/pkg/models"
	"sparrow/pkg/rpcs"

	"os"
	"strings"

	"sparrow/pkg/server"
)

func addApplication() error {
	args := models.Application{}

	reader := bufio.NewReader(os.Stdin)

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

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

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

	fmt.Printf("application report url: ")
	url, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	args.ReportUrl = strings.TrimSpace(url)

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

	reply := &models.Application{}

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

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

	return nil
}

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

	return nil
}
