package logger

import (
	"fmt"
	pterror "git.markbailey.dev/cervers/ptpp/lib/error"
	"git.markbailey.dev/cervers/ptpp/util"
	"log"
	"os"
	"sync"
)

var (
	dbLog         *Log
	dbLogFile     *os.File
	dbLoggerLock  = &sync.Mutex{}
	dbLogFileLock = &sync.Mutex{}
)

type DBLogger struct{}

func NewDBLogger() *DBLogger {
	return &DBLogger{}
}

func (l DBLogger) GetLogger() *Log {
	if dbLog == nil {
		dbLoggerLock.Lock()
		defer dbLoggerLock.Unlock()

		logFile := l.getLogFile()

		dbLog = &Log{
			Error: log.New(logFile, "ERROR:\t", log.Ldate|log.Ltime),
			Warn:  log.New(logFile, "WARN:\t", log.Ldate|log.Ltime),
			Info:  log.New(logFile, "INFO:\t", log.Ldate|log.Ltime),
		}
	}

	return dbLog
}

func (l DBLogger) getLogFile() *os.File {
	if dbLogFile == nil {
		dbLogFileLock.Lock()
		defer dbLogFileLock.Unlock()

		absPath := util.GetFullyQualifiedPath("/log")

		generalLog, err := os.OpenFile(absPath+"/db-log.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			fmt.Println("Error opening file:", err)
			os.Exit(1)
		}

		dbLogFile = generalLog
	}

	return dbLogFile
}

func (l DBLogger) Error(e error) {
	l.GetLogger().Error.Println(e)
}

func (l DBLogger) Warn(w string) {
	l.GetLogger().Warn.Println(w)
}

func (l DBLogger) Info(i string) {
	l.GetLogger().Info.Println(i)
}

func (l DBLogger) Wrap(e error, context string) error {
	return pterror.Wrap(e, context)
}
