package galog

import (
	"errors"
	"fmt"
	"os"
	"strings"
)

type ServerLogOptions struct {
	// LogDir 日志目录，默认logs
	LogDir string

	// EnableAsync 是否开启异步写日志，默认开启
	EnableAsync bool

	// AsyncQueueSize 异步队列大小，默认1000
	AsyncQueueSize int64
}

// NewServerLogger 业务日志实例，support JSON
//
//	opts.LogDir 日志目录，推荐logs
//	opts.EnableAsync 是否开启异步写日志，默认开启
//	opts.AsyncQueueSize 异步队列大小，默认1000
//	useage: logger.BizErr(map[string]interface{}{"type": "test"})
func NewServerLogger(opts *ServerLogOptions) (*Logger, error) {
	if opts == nil {
		opts = &ServerLogOptions{
			LogDir:         "logs",
			EnableAsync:    true,
			AsyncQueueSize: 1000,
		}
	}
	if opts.LogDir == "" {
		opts.LogDir = "logs"
	}
	if opts.EnableAsync && opts.AsyncQueueSize == 0 {
		opts.AsyncQueueSize = 1000
	}

	l := newLogger()
	hostname, _ := os.Hostname()
	filename := fmt.Sprintf("server_%s.log", hostname)
	configs := fmt.Sprintf(`{"filename":"%s/%s"}`, strings.TrimRight(opts.LogDir, "/"), filename)
	err := l.setLogger(AdapterFile, configs)
	if err != nil {
		return nil, err
	}
	if opts.EnableAsync && opts.AsyncQueueSize > 0 {
		l.Async(opts.AsyncQueueSize)
	}
	return l, nil
}

type ServerGALogOptions struct {
	// LogDir 日志目录，默认galogs
	LogDir string

	// EnableAsync 是否开启异步写日志，默认开启
	EnableAsync bool

	// AsyncQueueSize 异步队列大小，默认1000
	AsyncQueueSize int64

	// GA侧分配ProjectID
	ProjectID string

	// GA侧分配ClientID
	ClientID string

	LogType LogType
}

// NewServerGALogger GA日志实例，support JSON
//
//	opts.ProjectID 项目ID，GA侧分配，必填
//	opts.ClientID 客户端ID，GA侧分配，必填
//	opts.LogType 日志类型，默认LogTypeTrack
//	opts.LogDir 日志目录，默认galogs
//	opts.EnableAsync 是否开启异步写日志，默认开启
//	opts.AsyncQueueSize 异步队列大小，默认1000
func NewServerGALogger(opts *ServerGALogOptions) (*GALogger, error) {
	if opts == nil {
		return nil, errors.New("opts must not be empty")
	}
	if opts.EnableAsync && opts.AsyncQueueSize == 0 {
		opts.AsyncQueueSize = 1000
	}
	if opts.LogDir == "" {
		opts.LogDir = "galogs"
	}
	if opts.LogType == "" {
		opts.LogType = LogTypeTrack
	}
	if opts.ProjectID == "" || opts.ClientID == "" {
		return nil, errors.New("projectID or clientID must not be empty")
	}

	l := newLogger()
	hostname, _ := os.Hostname()
	filename := fmt.Sprintf("ga_%s.log", hostname)
	if opts.LogType == LogTypeAsset {
		filename = fmt.Sprintf("asset_%s.log", hostname)
	}
	configs := fmt.Sprintf(`{"filename":"%s/%s"}`, strings.TrimRight(opts.LogDir, "/"), filename)
	err := l.setLogger(AdapterFile, configs)
	if err != nil {
		return nil, err
	}
	if opts.EnableAsync && opts.AsyncQueueSize > 0 {
		l.Async(opts.AsyncQueueSize)
	}
	gaLogger := &GALogger{
		logger:    l,
		projectID: opts.ProjectID,
		clientID:  opts.ClientID,
		logType:   opts.LogType,
	}

	return gaLogger, nil
}
