package events

import (
	"encoding/json"
	"time"

	"github.com/segmentio/fasthash/fnv1a"
)

// TimeWindow Time interval
type TimeWindow struct {
	Begin time.Time
	End   time.Time
}

// NewTimeWindowFromNow Create new time window from now to now+duration
func NewTimeWindowFromNow(duration time.Duration) TimeWindow {
	now := time.Now().UTC()
	return TimeWindow{
		Begin: now,
		End:   now.Add(duration),
	}
}

// Hash Calculate time window hash
func (window *TimeWindow) Hash() uint32 {
	var hash uint32
	hash = fnv1a.AddString32(hash, window.Begin.Format("2006-01-02T15:04:05"))
	hash = fnv1a.AddString32(hash, window.End.Format("2006-01-02T15:04:05"))
	return hash
}

func (window TimeWindow) String() string {
	bytes, err := json.Marshal(window)
	if err != nil {
		return ""
	}

	return string(bytes)
}
