package lib

import (
	"fmt"
	"io"
	"os"
	"runtime"
	"time"
)

var debugEnabled = false
var debugFile = "debug.log"
var debugLogger *DebugLogger

type DebugLogger struct {
	file *os.File
}

func EnableDebug(enable bool) {
	debugEnabled = enable
}

func GetDebugLogger() *DebugLogger {
	if debugLogger == nil {
		debugLogger = &DebugLogger{}
		runtime.SetFinalizer(
			debugLogger, func(logger *DebugLogger) {
				logger.Close()
			},
		)

		if debugEnabled {
			var err error
			_, err = os.Stat(debugFile)

			if err != nil {
				debugLogger.file, _ = os.Create(debugFile)
			} else {
				debugLogger.file, _ = os.OpenFile(debugFile, os.O_RDWR, 0644)
				debugLogger.file.Seek(0, io.SeekEnd)
			}
		}
	}

	return debugLogger
}

func (l *DebugLogger) Log(msg ...any) {
	if l.file == nil {
		return
	}

	l.file.WriteString(fmt.Sprintln(append([]any{time.Now().Format("2006-01-02 15:04:05")}, msg...)...))
}

func (l *DebugLogger) Close() error {
	if l.file == nil {
		return nil
	}

	return l.file.Close()
}
