package oldreport

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

	"github.com/gin-gonic/gin"
	"github.com/onsi/gomega"

	apierr "github.com/pingcap-inc/clinic/pkg/api/error"
	"github.com/pingcap-inc/clinic/pkg/auth/session"
	"github.com/pingcap-inc/clinic/pkg/config"
	"github.com/pingcap-inc/clinic/pkg/task_manager"
)

var (
	cli     = &task_manager.TaskManagerClient{}
	service = ReportService{
		cfg: &config.Config{
			ReportConfig: config.ReportConfig{
				ComputeEngineEndPoint: "https://ctd1rbkuai.execute-api.us-west-2.amazonaws.com/prod",
			},
		},
		taskManager: cli,
	}
)

func setHandler(m string, method func(c *gin.Context), params []gin.Param, body []byte, query string) (int, []byte) {
	w := httptest.NewRecorder()
	context, _ := gin.CreateTestContext(w)
	context.Set(session.CtxUserKey, &session.CtxUser{
		Username:        "test_user01",
		UserID:          1,
		Email:           "test01",
		Internal:        true,
		OrgIDInApiToken: 1,
	})
	switch m {
	case http.MethodGet:
		context.Request = httptest.NewRequest(http.MethodGet, service.cfg.GetComputeEngineEndPoint()+query, nil)
		context.Params = params
	case http.MethodPost:
		context.Request = httptest.NewRequest(http.MethodPost, service.cfg.GetComputeEngineEndPoint()+query, bytes.NewReader(body))
		context.Params = params
		context.Request.Header.Set("Content-Type", "application/json")
	case http.MethodPut:
		context.Request = httptest.NewRequest(http.MethodPut, service.cfg.GetComputeEngineEndPoint()+query, bytes.NewReader(body))
		context.Params = params
		context.Request.Header.Set("Content-Type", "application/json")
	case http.MethodDelete:
		context.Request = httptest.NewRequest(http.MethodDelete, service.cfg.GetComputeEngineEndPoint()+query, bytes.NewReader(body))
		context.Params = params
		context.Request.Header.Set("Content-Type", "application/json")
	default:
		panic(fmt.Errorf("unknow http method"))
	}
	method(context)
	apierr.ErrorHandlerFn(context)
	data := w.Body.String()
	return w.Code, []byte(data)
}

func TestListHealthReport(t *testing.T) {
	g := gomega.NewWithT(t)
	loc, _ := time.LoadLocation("Asia/Shanghai")
	beginTime, _ := time.ParseInLocation("2006-01-02 15:04:05", "2018-07-11 15:07:51", loc)
	endTime, _ := time.ParseInLocation("2006-01-02 15:04:05", "2018-07-12 15:07:51", loc)
	params := []gin.Param{
		{
			Key:   "oid",
			Value: "1",
		},
		{
			Key:   "cid",
			Value: "Test_01_0",
		},
	}
	query := fmt.Sprintf("?startTime=%d&endTime=%d&brief=true", beginTime.Unix(), endTime.Unix())
	status, body := setHandler("GET", service.ListHealthReport, params, nil, query)
	g.Expect(status).To(gomega.Equal(http.StatusOK))
	reportRes := &HealthReportResp{}
	err := json.Unmarshal(body, reportRes)
	g.Expect(err).To(gomega.Succeed())
}
