package logparse

import (
	"encoding/json"
	"time"
)

const iso8601Nano = "2006-01-02T15:04:05Z07:00"

// Time is a json marshallable time.Time. Value truncated to
// nanosecond accuracy and time zone stripped.
type Time time.Time

// MarshalJSON implements json.Marshaller
func (t Time) MarshalJSON() ([]byte, error) {
	return json.Marshal(time.Time(t).Format(iso8601Nano))
}

// UnmarshalJSON implements json.Unmarshaller
func (t *Time) UnmarshalJSON(data []byte) (err error) {
	var asStr string
	if err = json.Unmarshal(data, &asStr); err != nil {
		return err
	}

	rawTime, err := time.Parse(iso8601Nano, asStr)
	if err != nil {
		return err
	}

	*t = Time(rawTime.UTC())
	return nil
}
