package callgraph

import (
	"math"
	"time"

	"code.justin.tv/release/trace/pbmsg"
)

func isRequestEvent(e *pbmsg.Event) bool {
	requestKinds := []pbmsg.Event_Kind{
		pbmsg.Event_REQUEST_HEAD_PREPARED,
		pbmsg.Event_REQUEST_BODY_SENT,
		pbmsg.Event_REQUEST_HEAD_RECEIVED,
		pbmsg.Event_REQUEST_BODY_RECEIVED,
	}
	ek := e.GetKind()
	for _, k := range requestKinds {
		if k == ek {
			return true
		}
	}
	return false
}

func isResponseEvent(e *pbmsg.Event) bool {
	responseKinds := []pbmsg.Event_Kind{
		pbmsg.Event_RESPONSE_HEAD_PREPARED,
		pbmsg.Event_RESPONSE_BODY_SENT,
		pbmsg.Event_RESPONSE_HEAD_RECEIVED,
		pbmsg.Event_RESPONSE_BODY_RECEIVED,
	}
	ek := e.GetKind()
	for _, k := range responseKinds {
		if k == ek {
			return true
		}
	}
	return false
}

func isClientEvent(e *pbmsg.Event) bool {
	clientKinds := []pbmsg.Event_Kind{
		pbmsg.Event_REQUEST_HEAD_PREPARED,
		pbmsg.Event_REQUEST_BODY_SENT,
		pbmsg.Event_RESPONSE_HEAD_RECEIVED,
		pbmsg.Event_RESPONSE_BODY_RECEIVED,
	}
	ek := e.GetKind()
	for _, k := range clientKinds {
		if k == ek {
			return true
		}
	}
	return false
}

func isServerEvent(e *pbmsg.Event) bool {
	serverKinds := []pbmsg.Event_Kind{
		pbmsg.Event_REQUEST_HEAD_RECEIVED,
		pbmsg.Event_REQUEST_BODY_RECEIVED,
		pbmsg.Event_RESPONSE_HEAD_PREPARED,
		pbmsg.Event_RESPONSE_BODY_SENT,
	}
	ek := e.GetKind()
	for _, k := range serverKinds {
		if k == ek {
			return true
		}
	}
	return false
}

func maxTime(events []*pbmsg.Event) time.Time {
	var ns int64 = math.MinInt64
	for _, e := range events {
		if e.GetTime() > ns {
			ns = e.GetTime()
		}
	}
	return time.Unix(0, ns)
}

func minTime(events []*pbmsg.Event) time.Time {
	var ns int64 = math.MaxInt64
	for _, e := range events {
		if e.GetTime() < ns {
			ns = e.GetTime()
		}
	}
	return time.Unix(0, ns)
}

func eventsWithKinds(events []*pbmsg.Event, kinds []pbmsg.Event_Kind) []*pbmsg.Event {
	out := make([]*pbmsg.Event, 0)
	for _, e := range events {
		for _, k := range kinds {
			if e.GetKind() == k {
				out = append(out, e)
			}
		}
	}
	return out
}
