// database initial and migrate
package mysql

import (
	"fmt"
	"sparrow/pkg/models"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

func MigrateDatabase(dbhost, dbport, dbname, dbuser, dbpass string) error {
	mysqldb, err := GetClient(dbhost, dbport, dbname, dbuser, dbpass)
	if err != nil {
		return err
	}
	db, err := gorm.Open("mysql", mysqldb)
	if err != nil {
		return err
	}

	// Then you could invoke `*sql.DB`'s functions with it
	err = db.DB().Ping()
	if err != nil {
		return err
	}

	// Disable table name's pluralization
	db.SingularTable(true)
	db.LogMode(false)
	// Automating Migration
	err = db.Set("gorm:table_options", "ENGINE=MyISAM").AutoMigrate(
		&models.Device{},
		&models.Product{},
		&models.Sensor{},
		&models.Vendor{},
		&models.Application{},
		&models.Rule{},
		&models.User{},
		&models.Privilege{},
		&models.Role{},
		&models.Protocal{},
		&models.AlarmRule{},
		&models.Menu{},
		&models.Event{},
		&models.Relation{},
		&models.RuleNode{},
		&models.RuleChain{},
		&models.DeviceNetConfig{},
		&models.SubDevice{},
		&models.Ota{},
		&models.SceneHis{},
		&models.DeviceCommand{},
		&models.DeviceCommandData{},
		&models.DeviceStatus{},
		&models.DeviceStatusData{},
	).Error
	if err != nil {
		fmt.Printf("%s", err.Error())
	}

	return nil
}
