package api

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"code.justin.tv/video/spectre/auth/authtest"
	"code.justin.tv/video/spectre/backend"
	"code.justin.tv/video/spectre/backend/backendtest"
	. "github.com/smartystreets/goconvey/convey"
	"github.com/zenazn/goji/web"
)

func performShowChannelRequest(c web.C) *httptest.ResponseRecorder {
	router := Router{Backend: backendtest.NewBackend(), AuthHandler: authtest.NewHandler()}
	w := httptest.NewRecorder()

	r, _ := http.NewRequest("", "", nil)
	router.ShowChannel(c, w, r)
	return w
}

func TestShowChannel(t *testing.T) {
	Convey("shows a valid channel", t, func() {
		c := web.C{URLParams: map[string]string{
			"channel_id": "10",
		}}

		w := performShowChannelRequest(c)
		So(w.Code, ShouldEqual, http.StatusOK)
	})

	Convey("show a default channel for missing channel", t, func() {
		c := web.C{URLParams: map[string]string{
			"channel_id": "5000",
		}}
		w := performShowChannelRequest(c)
		So(w.Code, ShouldEqual, http.StatusOK)
		So(w.Body.String(), ShouldContainSubstring, `"enabled":false`)
	})
}

func performUpdateChannelRequest(c web.C, body backend.ChannelParams) *httptest.ResponseRecorder {
	router := Router{Backend: backendtest.NewBackend(), AuthHandler: authtest.NewHandler()}
	w := httptest.NewRecorder()

	requestBody, _ := json.Marshal(body)
	r, _ := http.NewRequest("", "", bytes.NewBuffer(requestBody))

	router.UpdateChannel(c, w, r)
	return w
}

func TestUpdateChannel(t *testing.T) {
	c := web.C{URLParams: map[string]string{
		"channel_id": "10",
	}}
	// Convey("updates a valid channel", t, func() { TODO: fix test
	// 	body := backend.ChannelParams{
	// 		Enabled: false,
	// 	}

	// 	w := performUpdateChannelRequest(c, body)
	// 	So(w.Code, ShouldEqual, http.StatusOK)
	// 	So(w.Body.String(), ShouldContainSubstring, `"enabled":false`)
	// })
	Convey("returns 200 when no updates should be made", t, func() {

		body := backend.ChannelParams{
			Enabled: true,
		}

		w := performUpdateChannelRequest(c, body)
		So(w.Code, ShouldEqual, http.StatusOK)
		So(w.Body.String(), ShouldContainSubstring, `"enabled":true`)
	})
	Convey("200s for nonexistent channel", t, func() {
		// Spectre has no way of knowing if a channel exists or not. We assume every channel exists, so we 200 here
		c := web.C{URLParams: map[string]string{
			"channel_id": "5000",
		}}

		body := backend.ChannelParams{
			Enabled: false,
		}

		w := performUpdateChannelRequest(c, body)
		So(w.Code, ShouldEqual, http.StatusOK)
	})
}
