package idec

import (
	"strconv"
	"strings"

	idec "github.com/idec-net/go-idec"
)

// ParseMessage ...
func ParseMessage(message string) (Message, error) {
	var m Message

	msg, err := idec.ParseMessage(message)
	if err != nil {
		return m, err
	}

	m.Tags = msg.Tags.II
	m.Echo = msg.Echo
	m.Timestamp = msg.Timestamp
	m.From = msg.From
	m.Address = msg.Address
	m.To = msg.To
	m.Subg = msg.Subg
	m.Body = msg.Body
	m.Repto = msg.Tags.Repto
	m.ID = msg.ID

	return m, err
}

// ParseEchoList parse /list.txt
func ParseEchoList(list string) ([]Echo, error) {
	var echoes []Echo
	for _, e := range strings.Split(list, "\n") {
		desc := strings.Split(e, ":")
		if len(desc) <= 1 {
			break
		}
		count, err := strconv.Atoi(desc[1])
		if err != nil {
			return echoes, err
		}
		echoes = append(echoes, Echo{desc[0], count, desc[2]})
	}

	return echoes, nil
}
