package models

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql" // Because.
	"github.com/go-xorm/core"
	"github.com/go-xorm/xorm"
	_ "github.com/mattn/go-sqlite3" // Because.
)

var x *xorm.Engine

func getEngine() (*xorm.Engine, error) {
	// Use Mysql if set
	if Config.Database.Type == "mysql" {
		connStr := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true",
			Config.Database.User, Config.Database.Password, Config.Database.Host, Config.Database.Database)
		return xorm.NewEngine("mysql", connStr)
	}

	// Otherwise use sqlite
	path := Config.Database.Path
	if path == "" {
		path = "./db.db"
	}
	return xorm.NewEngine("sqlite3", path)
}

// SetEngine sets the xorm.Engine
func SetEngine() (err error) {
	x, err = getEngine()
	if err != nil {
		return fmt.Errorf("Failed to connect to database: %v", err)
	}

	// Cache
	cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
	x.SetDefaultCacher(cacher)

	x.SetMapper(core.GonicMapper{})

	// Sync dat shit
	x.Sync(&Book{})
	x.Sync(&User{})
	x.Sync(&Publisher{})
	x.Sync(&Author{})
	x.Sync(&AuthorBook{})
	x.Sync(&Status{})
	x.Sync(&Quantity{})
	x.Sync(&quantityRelation{})
	x.Sync(&Item{})
	x.Sync(&UserLog{})

	x.ShowSQL(Config.Database.ShowQueries)

	// Check if the first user already exists, aka a user with the ID = 1. If not, insert it
	_, exists, err := GetUserByID(1)
	if err != nil {
		return err
	}

	// If it doesn't exist, create it
	if !exists {
		_, err = CreateUser(Config.FirstUser)
		if err != nil {
			// Janky hack, I know
			if err.Error() != "this username is already taken. Please use another" {
				return err
			}
		}
		fmt.Println("Created new user " + Config.FirstUser.Username)
	}

	return nil
}
