package db

import (
	"fmt"
	"log"

	"git.sp4ke.com/sp4ke/bit4sat/config"
	_ "github.com/lib/pq"

	//_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"github.com/mediocregopher/radix/v3"
)

const (
	DBName = "bit4sat"
)

var (
	DB *Database
)

type Database struct {
	Sql         *sqlx.DB
	Redis       *radix.Pool
	RedisPubSub radix.PubSubConn
}

func (d *Database) Open() error {
	var err error

	dsn := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable",
		config.SqlDbUser,
		config.SqlDbPass,
		config.SqlDbHost,
		DBName)

	log.Printf("Opening SQL at %s\n", dsn)

	d.Sql = sqlx.MustConnect("postgres", dsn)

	// Execute Pragmas
	//d.Sql.MustExec(DBPragma)

	// Opend redis
	d.Redis, err = radix.NewPool("tcp", "redis:6379", 10)
	if err != nil {
		log.Fatal(err)
	}

	d.RedisPubSub = radix.PersistentPubSub("tcp", "redis:6379", nil)

	return nil
}

func RollbackTx(tx *sqlx.Tx, callback func()) {
	log.Println("Rolling back transactions !")
	err := tx.Rollback()
	if err != nil {
		log.Fatal(err)
	}

	if callback != nil {
		callback()
	}
}

func init() {
	DB = &Database{}
	DB.Open()

}
