package fetchconf

import (
	"archive/tar"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"
	"testing"

	"github.com/DataDog/zstd"
	"github.com/onsi/gomega"

	"github.com/pingcap-inc/clinic/pkg/cluster"
	"github.com/pingcap-inc/clinic/pkg/importer/log"
	"github.com/pingcap-inc/clinic/pkg/importer/metrics"
	"github.com/pingcap-inc/clinic/pkg/importer/utils"
)

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

	clusterInfo, err := log.TestClusterJSON("../testdata/cluster.json")
	g.Expect(err).To(gomega.Succeed())

	clusterID := "1"
	fileUUID := "123"
	sink, err := NewFetchConfSink(clusterID, fileUUID, nil)
	g.Expect(err).To(gomega.Succeed())
	sink.disablePersistent = true

	err = utils.ReadTar("../testdata/test.tar", func(fileName string, fh *tar.Header, r io.Reader) {
		filePath, err := utils.TmpFile(r)
		g.Expect(err).To(gomega.Succeed())
		if IsConfFile(fh.Name, fileName, cluster.NewImportComponentsMeta(clusterInfo)) {
			hdr := &tar.Header{
				Name:     fh.Name,
				Mode:     fh.Mode,
				Size:     fh.Size,
				Typeflag: fh.Typeflag,
				Uid:      fh.Uid,
				Gid:      fh.Gid,
				Uname:    fh.Uname,
				Gname:    fh.Gname,
				Format:   fh.Format,
			}

			task := NewFetchConfTask(sink, hdr, &metrics.TaskOption{
				// Status:            status.NewStatus(),
				FilePath:          filePath,
				FileSize:          fh.Size,
				OriginalPathInTar: fh.Name,
				ClusterID:         clusterID,
				FileUUID:          fileUUID,
			})
			task.Run()
		}
	})
	g.Expect(err).To(gomega.Succeed())
	sink.Close()

	newtar, err := os.Open(sink.zstdFilePath)
	g.Expect(err).To(gomega.Succeed())
	zr := zstd.NewReader(newtar)
	defer func() {
		zr.Close()
	}()
	g.Expect(err).To(gomega.Succeed())

	var clusterJSONData []byte
	err = utils.ReadTarWithReader(tar.NewReader(zr), func(fileName string, fh *tar.Header, r io.Reader) {
		fmt.Println(fh.Name)
		data, err := io.ReadAll(r)
		g.Expect(err).To(gomega.Succeed())
		g.Expect(strings.Contains(fh.Name, "/log")).To(gomega.BeFalse())
		g.Expect(strings.Contains(fh.Name, metrics.SubMonitorDir)).To(gomega.BeFalse())
		if strings.HasSuffix(fh.Name, "cluster.json") {
			clusterJSONData = data
		}
	})
	g.Expect(err).To(gomega.Succeed())
	var cj ClusterJSON
	err = json.Unmarshal(clusterJSONData, &cj)
	g.Expect(err).To(gomega.Succeed())

	g.Expect(cj.ClusterName).To(gomega.Equal("saos-htap-tidb-cluster-prod"))
	fmt.Println(sink.file.Name())
}

// copy from "github.com/pingcap/diag/collector"
type ClusterJSON struct {
	DiagVersion string   `json:"diag_version"`
	ClusterName string   `json:"cluster_name"`
	ClusterID   int64    `json:"cluster_id"`   // the id from pd
	ClusterType string   `json:"cluster_type"` // tidb-cluster or dm-cluster
	DeployType  string   `json:"deploy_type"`  // deployment type
	Session     string   `json:"session"`
	BeginTime   string   `json:"begin_time"`
	EndTime     string   `json:"end_time"`
	Collectors  []string `json:"collectors"`
	// Topology    *models.TiDBCluster `json:"topology"` // abstract cluster topo
}
