package fetchconf

import (
	"archive/tar"
	"os"
	"strings"

	"github.com/pingcap/log"
	"go.uber.org/zap"

	"github.com/pingcap-inc/clinic/pkg/cache"
	"github.com/pingcap-inc/clinic/pkg/cluster"
	_const "github.com/pingcap-inc/clinic/pkg/const"
	"github.com/pingcap-inc/clinic/pkg/importer/metrics"
)

type FetchConfTask struct {
	*metrics.TaskOption
	sink   *FetchConfSink
	header *tar.Header
}

func NewFetchConfTask(sink *FetchConfSink, header *tar.Header, opt *metrics.TaskOption) *FetchConfTask {
	return &FetchConfTask{
		TaskOption: opt,
		sink:       sink,
		header:     header,
	}
}

func (ft *FetchConfTask) Run() {
	//defer func() {
	//	ft.sink.Close()
	//}()
	//
	//f, err := os.Open(ft.PackagePath)
	//if err != nil {
	//	log.Error("open tar path failed", zap.String("path", ft.PackagePath), zap.Error(err))
	//	return
	//}
	//defer func() {
	//	f.Close()
	//}()
	//
	//reader := tar.NewReader(f)
	//
	//cb := func(err error) {
	//	if ft.Callback != nil {
	//		ft.Callback(err)
	//	}
	//}
	defer func() {
		cache.TaskStatusCache.Done(cache.TaskID(ft.FileUUID, _const.RebuildConfTask), ft.FileSize)
		log.Info("complete to rebuild configuration package", zap.String("fileUUID", ft.FileUUID))
		//_ = os.Remove(ft.FilePath)
	}()

	r, err := os.Open(ft.FilePath)
	if err != nil {
		log.Error("open tmp file failed", zap.String("fileUUID", ft.FileUUID), zap.Error(err))
		return
	}
	defer func() {
		_ = r.Close()
	}()

	ft.sink.Sink(ft.header, r)
}

func IsConfFile(path, fileName string, componentsMeta *cluster.ComponentsMeta) bool {
	if strings.Contains(path, metrics.SubMonitorDir) {
		return false
	}

	_, ok := componentsMeta.IsLog(path)
	if ok {
		if !strings.Contains(fileName, "stderr") {
			return false
		}
	}

	return true
}

// todo add stderr filter
func IsStderrLog(fileName string) bool {
	return strings.Contains(fileName, "stderr")
}
