package database

import (
	"fmt"
	"log"
	"time"

	"git.paulbsd.com/paulbsd/qrz/src/config"
	"git.paulbsd.com/paulbsd/qrz/src/qrz"
	"xorm.io/xorm"
	"xorm.io/xorm/names"
)

// Initialize creates connection to database and exec Schema
func Initialize(config *config.Config) (err error) {
	var connstr string
	switch config.DbType {
	case "sqlite3":
		connstr = fmt.Sprintf("%s", config.DbName)
	case "mysql":
		connstr = fmt.Sprintf("%s:%s@%s/%s",
			config.DbUsername,
			config.DbPassword,
			config.DbHostname,
			config.DbName)
	default:
		// postgresql by default
		connstr = fmt.Sprintf("%s://%s:%s@%s/%s",
			config.DbType,
			config.DbUsername,
			config.DbPassword,
			config.DbHostname,
			config.DbName)
	}

	for {
		log.Println("connecting to database")
		config.Db, err = xorm.NewEngine(config.DbType, connstr)
		if err != nil {
			time.Sleep(1 * time.Second)
		} else {
			break
		}
	}

	config.Db.SetMapper(names.GonicMapper{})

	err = config.Db.CreateTables(qrz.Qrz{})
	if err != nil {
		log.Fatalln(err)
	}

	err = config.Db.Sync2(qrz.Qrz{})
	if err != nil {
		log.Fatalln(err)
	}

	config.Db.ShowSQL(config.Debug)

	return
}
