package imports

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/tidbcloud/infra-api/pkg/k8s"

	"github.com/BurntSushi/toml"
	. "github.com/onsi/gomega"
)

func TestLightningClientCreateTask(t *testing.T) {
	g := NewGomegaWithT(t)
	taskJsonStr := fmt.Sprintf(`{
		"s": 2,
		"t": {
		  "%s": {
			"w": 0,
			"z": 41000,
			"s": 2,
			"m": "RequestCanceled: request context canceled\ncaused by: context canceled\ngithub.com/pingcap/errors/runtime/asm_amd64.s:1371\nrestore table %s failed"
		  },
		  "%s": {
			"w": 0,
			"z": 41000,
			"s": 2,
			"m": "RequestCanceled: request context canceled\ncaused by: context canceled\n\t/usr/local/go/src/runtime/asm_amd64.s:1371\nrestore table %s failed"
		  }
		},
		"m": "RequestCanceled: request context canceled\ncaused by: context canceled\n/home/jenkins/agent/workspace/build-common/gore.go:312\nruntime.goexit\n\t/usr/local/go/src/runtime/asm_amd64.s:1371\nrestore table %s failed"
	  }`, "`test`.`t1000`", "`test`.`t9`", "`test`.`t9`", "`test`.`t1000`", "`test`.`t1000`")
	taskInfoBytes := []byte(taskJsonStr)
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		t.Logf("%s %s", r.Method, r.URL.EscapedPath())
		if r.Method == "POST" && r.URL.EscapedPath() == "/tasks" {
			defer r.Body.Close()
			body, err := ioutil.ReadAll(r.Body)
			if err != nil {
				t.Fatal(err)
			}
			t.Logf("request:%s", body)
			var conf interface{}
			_, err = toml.Decode(string(body), &conf)
			if err != nil {
				t.Fatalf("failed to decode toml config %s %s", body, err)
			}
			var okresponse, _ = json.Marshal(conf)
			w.WriteHeader(http.StatusOK)
			_, err = w.Write(okresponse)
			if err != nil {
				t.Fatalf("failed to write %s", string(okresponse))
			}

			return
		} else if r.Method == "GET" && r.URL.EscapedPath() == "/progress/task" {

			w.WriteHeader(http.StatusOK)
			_, err := w.Write(taskInfoBytes)
			if err != nil {
				t.Fatalf("failed to write %s", string(taskInfoBytes))
			}
			return
		} else {
			t.Fatalf("Expected request to '/tasks /process/task', got '%s'", r.URL.EscapedPath())
		}

	}))
	defer ts.Close()
	t.Log(ts.URL)
	// simple create check
	lightningClient := newLightningClient(k8s.NewRawHTTPLinkNormal(context.Background(), ts.URL))
	rawID := int64(1111)
	id, err := lightningClient.CreateTask(fmt.Sprintf(`id = %d`, rawID))
	if err != nil {
		t.Errorf("create error %+v", err)
	}
	g.Expect(rawID).To(Equal(id))

	rawError := "fortesterror"
	// multi-line toml check
	// create error check
	multiline := fmt.Sprintf(`error="%s"
	[Mongo]
	connstr="localhost"
	dbname="blogs"
	usertab="users"
	blogtab="blogs"
	
	[servers]
	  ip = "localhost"
	  port = ":8086"
	`, rawError)
	// test error info
	id, err = lightningClient.CreateTask(multiline)
	if err != nil {
		g.Expect(rawError).To(Equal(err.Error()))
	}
	t.Log(id)

	// check the /process/tasks

	task, err := lightningClient.GetTaskProgress()
	if err != nil {
		g.Expect(err).To(Equal(""))
	}
	t.Log(task)

	rawTask := TaskProgress{}
	err = json.Unmarshal(taskInfoBytes, &rawTask)
	if err != nil {
		g.Expect(err).To(Equal(""))
	}
	g.Expect(rawTask).To(Equal(*task))

}

func init() {

}
