package jax

import (
	"net/url"
	"strconv"
	"strings"
)

type StreamOptions struct {
	Fields       []string
	ExistsFields []string
	Filters      []Filter
}

type StreamsOptions struct {
	Pagination   PaginationOptions
	Sort         string
	Fields       []string
	ExistsFields []string
	Filters      []Filter
}

type PaginationOptions struct {
	Limit  int
	Offset int
}

type Filter struct {
	field string
	value string
}

func EqualityFilter(field, value string) Filter {
	return Filter{
		field: field,
		value: value,
	}
}

func MaxHeightFilter(maxHeight string) Filter {
	return Filter{
		field: "usher.max_height",
		value: maxHeight,
	}
}

func XboxHeartbeatFilter(live bool) Filter {
	return Filter{
		field: "xbox_heartbeat",
		value: strconv.FormatBool(live),
	}
}

func StreamTypeFilter(streamType string) Filter {
	return Filter{
		field: "stream_type",
		value: streamType,
	}
}

func (R *StreamOptions) urlParams() url.Values {
	u := url.Values{}
	if R == nil {
		return u
	}

	if len(R.Fields) > 0 {
		u.Set("fields", strings.Join(R.Fields, ","))
	}

	if len(R.ExistsFields) > 0 {
		u.Set("exists_fields", strings.Join(R.ExistsFields, ","))
	}

	for _, f := range R.Filters {
		u.Set(f.field, f.value)
	}
	return u
}

func (R *StreamsOptions) urlParams() url.Values {
	u := url.Values{}
	if R == nil {
		return u
	}

	if R.Pagination.Limit > 0 {
		u.Set("size", strconv.Itoa(R.Pagination.Limit))
	}
	if R.Pagination.Offset > 0 {
		u.Set("from", strconv.Itoa(R.Pagination.Offset))
	}
	if len(R.Fields) > 0 {
		u.Set("fields", strings.Join(R.Fields, ","))
	}
	if len(R.ExistsFields) > 0 {
		u.Set("exists_fields", strings.Join(R.ExistsFields, ","))
	}
	if len(R.Sort) > 0 {
		u.Set("sort", R.Sort)
	}

	for _, f := range R.Filters {
		u.Set(f.field, f.value)
	}
	return u
}
