package usher

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"

	"github.com/stvp/rollbar"
)

type JaxQuery struct {
	Filters []*JaxFilter
}

type JaxFilter map[string]interface{}

func (T *JaxQuery) MarshalJSON() ([]byte, error) {
	myJson, _ := json.Marshal(map[string]interface{}{
		"filter": map[string][]*JaxFilter{
			"and": T.Filters,
		},
	})
	return myJson, nil
}

type Result struct {
	Total int         `json:"_total"`
	Hits  interface{} `json:"hits"`
}

// IsLive asks Jax if an individual channel is live
func (UsherService) IsLive(channelID int) (bool, error) {
	notSpectreFilter := JaxFilter{
		"not": map[string]map[string]string{"eq": {"usher.broadcaster": "spectre"}},
	}
	channelsFilter := JaxFilter{
		"eq": map[string][]int{"rails.channel_id": []int{channelID}},
	}
	myQuery := JaxQuery{
		Filters: []*JaxFilter{
			&notSpectreFilter,
			&channelsFilter,
		},
	}

	b, _ := json.Marshal(&myQuery)

	response, err := http.Post("http://jax-internal-production.us-west2.justin.tv/streams", "application/json", bytes.NewBuffer(b))
	if err != nil {
		rollbar.ErrorWithStack(rollbar.ERR, err, rollbar.BuildStack(0))
		return false, err
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return false, err
	}

	var r Result
	err = json.Unmarshal(body, &r)

	return r.Total > 0, nil
}
