package pttodo

import (
	"encoding/json"
	"errors"
	"time"

	yaml "gopkg.in/yaml.v2"
)

type TS int64

func (ts TS) time() time.Time {
	if ts == 0 {
		ts = TS(time.Now().Unix())
	}
	return time.Unix(int64(ts), 0)
}

func (ts TS) MarshalJSON() ([]byte, error) {
	v, err := ts.MarshalYAML()
	if err != nil {
		return nil, err
	}
	return json.Marshal(v)
}

func (ts TS) MarshalYAML() (interface{}, error) {
	if ts == 0 {
		ts = TS(time.Now().Unix())
	}
	return ts.time().Format(time.UnixDate), nil
}

func (ts *TS) UnmarshalJSON(b []byte) error {
	return yaml.Unmarshal(b, ts)
}

func (ts *TS) UnmarshalYAML(unmarshaller func(interface{}) error) error {
	var n int64
	if err := unmarshaller(&n); err == nil {
		*ts = TS(n)
		return nil
	}
	var s string
	if err := unmarshaller(&s); err == nil {
		t, err := time.ParseInLocation(time.UnixDate, s, time.Local)
		*ts = TS(t.Unix())
		return err
	}
	return errors.New("illegal TS")
}
