package common

import (
	"errors"
	"fmt"
	"github.com/getsentry/sentry-go"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

func NewLogger() (logger *zap.Logger) {

	path := ""

	if ok, _ := pathExists(path); !ok { // 判断是否有Director文件夹
		fmt.Printf("create %v directory\n", path)
		_ = os.Mkdir(path, os.ModePerm)
	}

	cores := Zap.GetZapCores()

	sCore := registerSentry()
	cores = append(cores, sCore)

	logger = zap.New(zapcore.NewTee(cores...))

	if CONFIG.Zap.ShowLine {
		logger = logger.WithOptions(zap.AddCaller())
	}

	return logger
}

func registerSentry() zapcore.Core {
	// sentrycore配置
	cfg := SentryCoreConfig{
		DisableStacktrace: false,
		Level:             zap.ErrorLevel,
		Tags: map[string]string{
			"app": "sec-cycle-scan",
			"env": AppEnv,
		},
	}

	dsn := CONFIG.System.SentryUrl

	// 生成sentry客户端
	sentryClient, err := sentry.NewClient(sentry.ClientOptions{
		Dsn:              dsn,
		Debug:            true,
		AttachStacktrace: true,
	})

	if err != nil {
		panic(fmt.Sprintf("sentry client creation failed :%s", err))
	}

	// 生成sentryCore 并追加
	return NewSentryCore(cfg, sentryClient)
}

func pathExists(path string) (bool, error) {
	fi, err := os.Stat(path)
	if err == nil {
		if fi.IsDir() {
			return true, nil
		}
		return false, errors.New("there is a file with the same name")
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
