package file_download

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

	"github.com/gin-gonic/gin"
	"github.com/onsi/gomega"
	"github.com/pingcap/log"
	"go.uber.org/zap"

	"github.com/pingcap-inc/clinic/pkg/ngm/file_download/api"
)

func TestLinkResp(t *testing.T) {
	g := gomega.NewWithT(t)

	data := api.ListData{Records: []api.ListFileRecord{
		{
			Instance: "tidb-0",
			Files: []api.FileMetaInfo{
				{
					Key:         "0/1/1379/80462/oom_record/tidb/1669624049/tidb-0/goroutine2022-11-28T16:27:29+08:00",
					DownloadURL: downloadPath("aws", "us-west-2", "0/1/1379/80462/oom_record/tidb/1669624049/tidb-0/goroutine2022-11-28T16:27:29+08:00"),
				},
			},
		},
	}}
	bs, err := json.Marshal(data)
	g.Expect(err).Should(gomega.Succeed())
	t.Log(string(bs))
	q, _ := url.QueryUnescape("0%2F1%2F1379%2F80462%2Foom_record%2Ftidb%2F1669624049%2Ftidb-0%2Fgoroutine2022-11-28T16%3A27%3A29%2B08%3A00")
	t.Log(q)
	log.Info("xxx", zap.String("q", q))
	c, _ := gin.CreateTestContext(httptest.NewRecorder())
	c.Request = httptest.NewRequest(http.MethodGet, "http://localhost", nil)
	c.Request.URL.Path = "/ngm/api/v1/oom_record/"
	c.Request.URL.RawQuery = "provider=aws&region=us-west-2&key=0%2F1%2F1379%2F80462%2Foom_record%2Ftidb%2F1669624049%2Ftidb-0%2Fgoroutine2022-11-28T16%3A27%3A29%2B08%3A00"
	t.Log(c.Query("key"))
}

func TestParseMetaFromKey(t *testing.T) {
	g := gomega.NewWithT(t)

	ts, instance, fname := parseMetaFromKey("1669624049/tidb-0/goroutine2022-11-28T16:27:29+08:00")
	g.Expect(ts).Should(gomega.Equal(int64(1669624049)))
	g.Expect(instance).Should(gomega.Equal("tidb-0"))
	g.Expect(fname).Should(gomega.Equal("goroutine2022-11-28T16:27:29+08:00"))
}
