package logger

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

var (
	concreteCompositeLog *Log
	compositeLogFile     *os.File
	compositeLoggerLock  = &sync.Mutex{}
	compositeLogFileLock = &sync.Mutex{}
)

type CompositeLogger struct{}

func NewCompositeLogger() *CompositeLogger {
	return &CompositeLogger{}
}

func (l CompositeLogger) GetLogger() *Log {
	if concreteCompositeLog == nil {
		compositeLoggerLock.Lock()
		defer compositeLoggerLock.Unlock()

		logFile := l.getLogFile()

		concreteCompositeLog = &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 concreteCompositeLog
}

func (l CompositeLogger) getLogFile() *os.File {
	if compositeLogFile == nil {
		compositeLogFileLock.Lock()
		defer compositeLogFileLock.Unlock()

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

		err := os.MkdirAll(absPath, os.ModePerm)
		if err != nil {
			fmt.Println("Error creating directory:", err)
			os.Exit(1)
		}

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

		compositeLogFile = generalLog
	}

	return compositeLogFile
}
func (l CompositeLogger) Error(e error) {
	l.GetLogger().Error.Println(e)
}

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

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

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