package logging

import (
	"exhibitionCentre/config"
	"log"
	"os"
	"time"

	"github.com/op/go-logging"
)

var Log = logging.MustGetLogger("HumbleAccount")

func init() {
	// If dir does not exist, create dir.
	if _, err := os.Stat("logs"); os.IsNotExist(err) {
		os.Mkdir("logs", os.ModePerm)
	}

	// create a new log file per week
	go RotateLogs(7 * 24 * time.Hour)
}

func StartNewLogger() *os.File {
	// create log file
	logName := "logs/log_" + time.Now().Format("2006-01-02") + ".log"
	logfile, err := os.OpenFile(logName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalf("error opening file: %v", err)
	}

	// create backends
	fileBackend := logging.NewLogBackend(logfile, "", 0)
	consoleBackend := logging.NewLogBackend(os.Stderr, "", 0)

	// create formatter backends
	fileFormatterBackend := logging.NewBackendFormatter(fileBackend, fileFormat)
	consoleFormatterBackend := logging.NewBackendFormatter(consoleBackend, consoleFormat)

	// read level
	levelName := config.Config.Log.Level
	loglevel, _ := logging.LogLevel(levelName)

	// create leveled backends
	fileLeveledBackend := logging.AddModuleLevel(fileFormatterBackend)
	fileLeveledBackend.SetLevel(loglevel, "")
	consoleLeveledBackend := logging.AddModuleLevel(consoleFormatterBackend)
	consoleLeveledBackend.SetLevel(loglevel, "")

	// Set the backends to be used.
	logging.SetBackend(fileLeveledBackend, consoleLeveledBackend)
	return logfile
}

var consoleFormat = logging.MustStringFormatter(
	`%{color}%{time:2006-01-02-15:04:05.000} ▶ %{level:.4s} %{shortfile} %{longfunc}: %{message}`,
)

var fileFormat = logging.MustStringFormatter(
	`%{time:2006-01-02-15:04:05.000} ▶ %{level:.4s} %{shortfile} %{longfunc}: %{message}`,
)
