package jsonutil

import (
	"encoding/json"
	"time"
)

// Duration is a json serializable duration
type Duration time.Duration

// MarshalJSON implements json.Marshaller
func (d Duration) MarshalJSON() ([]byte, error) {
	return json.Marshal(time.Duration(d).Seconds())
}

// UnmarshalJSON implements json.Unmarshaller
func (d *Duration) UnmarshalJSON(data []byte) error {
	var asFloat float64
	err := json.Unmarshal(data, &asFloat)
	if err != nil {
		return err
	}
	*d = Duration(time.Duration(asFloat) * time.Second)
	return nil
}
