package broker

import (
	"fmt"
	"local/storage"
	"local/truckstop/logtr"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"
	"testing"
	"time"

	"golang.org/x/time/rate"
)

func TestBrokerInterface(t *testing.T) {
	logtr.SetLevel(logtr.SOS)
	var b Broker
	b = FastExact{}
	b = NTGVision{}
	_ = b
}

func TestDoCookies(t *testing.T) {
	logtr.SetLevel(logtr.SOS)
	limiter = rate.NewLimiter(rate.Limit(20.0), 1)
	calls := 0
	db := storage.NewMap()
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		calls += 1
		if calls != 1 {
			if !strings.Contains(fmt.Sprint(r.Header["Cookie"]), "name=value"+strconv.Itoa(calls-1)) {
				w.WriteHeader(http.StatusBadRequest)
				t.Error("cookie not set as latest: " + fmt.Sprint(r.Header["Cookie"]))
			}
			if strings.Contains(fmt.Sprint(r.Header["Cookie"]), "Expires") {
				w.WriteHeader(http.StatusBadRequest)
				t.Error("cookie not expiration: ", r.Header["Cookie"])
			}
		}
		http.SetCookie(w, &http.Cookie{
			Name:    "name",
			Value:   "value" + strconv.Itoa(calls),
			Expires: time.Now().Add(time.Hour),
		})
	}))
	defer s.Close()
	req, _ := http.NewRequest(http.MethodGet, s.URL, nil)

	if cookies, err := getCookies(db, "cookies_"+req.URL.Host); err == nil {
		t.Fatal(err)
	} else if len(cookies) != 0 {
		t.Fatal(cookies)
	}

	for i := 0; i < 3; i++ {
		resp, err := _do(db, req)
		if err != nil {
			t.Fatal(err)
		}
		if resp.StatusCode != http.StatusOK {
			t.Fatal(resp.StatusCode)
		}
		resp.Body.Close()

		if cookies, err := getCookies(db, "cookies_"+req.URL.Host); err != nil {
			t.Fatal(err)
		} else if len(cookies) == 0 {
			t.Fatal(cookies)
		}
	}
}
