package main

import (
	"currenstore/config"
	"currenstore/database"
	"currenstore/handlers"
	"flag"
	"fmt"
	"os"

	"github.com/gofiber/fiber/v2"
	"github.com/mileusna/crontab"
	log "github.com/sirupsen/logrus"
)

func main() {
	var confpath string
	var err error
	flag.StringVar(&confpath, "config", "config_local.toml", "path to config file")
	flag.Parse()
	os.Setenv("CURRENSTORE_CONF_PATH", confpath)
	var conf = config.InitConf(os.Getenv("CURRENSTORE_CONF_PATH"))

	initDatabase(conf)

	//Logger setup
	var filename string = conf.Server.AppLogPath
	f, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	Formatter := new(log.JSONFormatter)
	Formatter.TimestampFormat = "02-01-2006 15:04:05"
	log.SetFormatter(Formatter)
	if err != nil {
		fmt.Println(err)
	} else {
		log.SetOutput(f)
	}

	app := fiber.New()
	// Create a /api/v1 endpoint
	v1 := app.Group("/api/v1")

	// Bind handlers
	v1.Get("/ping", handlers.Healthcheck)
	v1.Get("/currency/:charcode/ondate/:ondate", handlers.GetCurrencyOnDate)
	v1.Get("/currency/restore/:startdate/to/:enddate", handlers.RestoreCurrencyData)
	v1.Get("/currency/:charcode/:startdate/to/:enddate", handlers.GetCurrencyOnDateInterval)
	v1.Get("/currency/:charcode/indate", handlers.GetCurrencyInDate)

	// Handle not founds
	app.Use(handlers.NotFound)

	//Crontask
	ctab := crontab.New() // create cron table

	// AddJob and test the errors
	log.Printf("Crontask expression %s", conf.Crontab.Exchangerateonday)
	err = ctab.AddJob(conf.Crontab.Exchangerateonday, handlers.GetAndSaveForToday)
	if err != nil {
		log.Println(err)
		return
	}

	// Listen on port 3000
	log.Fatal(app.Listen(":" + conf.Server.Port))
}

func initDatabase(conf config.Config) {
	err := config.ValidateDBEngine(conf.Database.Engine)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}
	if conf.Database.Engine == "sqlite" {
		database.DBConn = database.ConnectSQLite(conf.Database.DBFile)
		database.CheckTableSQLite(database.DBConn)

	}
}
