package test

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"path/filepath"
	"runtime"
	"sync"
	"testing"
	"time"
	_ "token-uri/routers"

	"github.com/astaxie/beego"
	. "github.com/smartystreets/goconvey/convey"
)

func init() {
	_, file, _, _ := runtime.Caller(0)
	apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".."+string(filepath.Separator))))
	beego.TestBeegoInit(apppath)
}

// TestBeego is a sample to run an endpoint test
func TestBeego(t *testing.T) {
	r, _ := http.NewRequest("GET", "/", nil)
	w := httptest.NewRecorder()
	beego.BeeApp.Handlers.ServeHTTP(w, r)

	beego.Trace("testing", "TestBeego", "Code[%d]\n%s", w.Code, w.Body.String())

	Convey("Subject: Test Station Endpoint\n", t, func() {
		Convey("Status Code Should Be 200", func() {
			So(w.Code, ShouldEqual, 200)
		})
		Convey("The Result Should Not Be Empty", func() {
			So(w.Body.Len(), ShouldBeGreaterThan, 0)
		})
	})
}

func TestGoRoutine(t *testing.T) {
	handlerIns := &handler{
		wg: &sync.WaitGroup{},
	}

	msg := make(chan int, 0)

	for i := 0; i < 2; i++ {
		go handlerMsg(handlerIns, msg, i)
	}
	for {
		i := 10
		if i%10 == 0 {
			time.Sleep(time.Second * 2)
			msg <- 1
		}
		i++
	}
}

type handler struct {
	wg *sync.WaitGroup
}

func handlerMsg(h *handler, msg chan int, count int) {
	for {
		fmt.Println("xxxx:", count)
		select {
		case rev := <-msg:
			{
				if rev == 1 {
					fmt.Println("exec   xxxx:", count)
					go func(h *handler) {
						h.wg.Add(1)
						h.handlerXXX()
						h.wg.Wait()
						fmt.Println("exec  task")
					}(h)
					continue
				}
			}
		}
	}
}

func (h *handler) handlerXXX() {
	defer h.wg.Done()
	time.Sleep(time.Second * 2)
	fmt.Println("wg done")
}
