package database

import (
	"context"
	"fmt"
	"log"
	"os"

	"git.paulbsd.com/paulbsd/ipbl/src/config"
	"git.paulbsd.com/paulbsd/ipbl/src/models"
	_ "github.com/lib/pq"
	"xorm.io/xorm"
	"xorm.io/xorm/dialects"
	"xorm.io/xorm/names"
)

func Initialize(ctx *context.Context, cfg *config.Config) (err error) {
	var databaseEngine = "postgres"
	//cacher := caches.NewLRUCacher(caches.NewMemoryStore(), 10)

	cfg.Db, err = xorm.NewEngine(databaseEngine,
		fmt.Sprintf("%s://%s:%s@%s/%s",
			databaseEngine,
			cfg.DbParams.DbUsername,
			cfg.DbParams.DbPassword,
			cfg.DbParams.DbHostname,
			cfg.DbParams.DbDatabase))
	if err != nil {
		log.Fatalln(err)
	}
	cfg.Db.SetMapper(names.GonicMapper{})
	cfg.Db.SetQuotePolicy(dialects.QuotePolicyReserved)
	cfg.Db.ShowSQL(cfg.Options.Debug)

	//cfg.Db.SetDefaultCacher(cacher)

	if cfg.Switchs.Drop {
		log.Println("Dropping tables")
		models.DropTables(ctx, cfg)
		os.Exit(0)
	}

	log.Println("Syncing tables")
	err = models.NewEngine(ctx, cfg)
	return
}
