package netsplit

import (
	`strings`
	`time`
)

// MarshalText lets an IANADate conform to an encoding.TextMarshaler.
func (i *IANADate) MarshalText() (text []byte, err error) {

	if i == nil {
		return
	}

	if time.Time(*i).Day() == 0 {
		text = []byte(time.Time(*i).Format(ianaMonthTfmt))
	} else {
		text = []byte(time.Time(*i).Format(ianaDateTfmt))
	}

	return
}

// UnmarshalText lets an IANADate conform to an encoding.TextUnmarshaler.
func (i *IANADate) UnmarshalText(text []byte) (err error) {

	var t time.Time

	if text == nil {
		return
	}

	switch len(string(text)) {
	case 7: // no day
		if t, err = time.Parse(
			ianaMonthTfmt,
			strings.TrimSpace(string(text)),
		); err != nil {
			return
		}
	default: // TECHNICALLY should be 10 but we'll let the error here catch it otherwise.
		if t, err = time.Parse(
			ianaDateTfmt,
			strings.TrimSpace(string(text)),
		); err != nil {
			return
		}
	}

	*i = IANADate(t)

	return
}