package fm

import (
	"fmt"
	"strings"

	"nms_nbi/lib/log"
	"nms_nbi/restagent/config"

	"github.com/chzyer/readline"
	"github.com/go-gsm/ucp"
)

func AlarmForwardBySMSC(alarmData *Alarm) error {
	opt := &ucp.Options{
		Addr:       config.GetYamlConfig().Alarm.SMSC.Addr,
		User:       config.GetYamlConfig().Alarm.SMSC.UserName,
		Password:   config.GetYamlConfig().Alarm.SMSC.Password,
		AccessCode: "",
	}

	client := ucp.New(opt)
	if err := client.Connect(); err != nil {
		log.Error("Failed to connect:", err)
		return err
	}
	defer client.Close()

	reader, _ := readline.New(">>> ")
	defer reader.Close()

	for {
		fmt.Print(">>> ")
		lines, _ := reader.Readline()
		fields := strings.Fields(lines)

		if len(fields) == 1 {
			// exit CLI
			if fields[0] == "exit" {
				return nil
			}
			// display help message
			if fields[0] == "help" {
				log.Trace("\n\tSend a 'message' to 'receiver' with a 'sender' mask\n\t>>> sender receiver message\n\n\tExit the cli\n\t>>> exit\n")
			}
		}

		// sender receiver message...
		if len(fields) >= 3 {
			sender := fields[0]
			receiver := fields[1]
			message := strings.Join(fields[2:], " ")
			ids, err := client.Send(sender, receiver, message)
			if err != nil {
				log.Error(err)
			} else {
				log.Debug("%v", ids)
			}
		}
	}
}
