package main

import (
	"git.kingpenguin.tk/chteufleur/datahouse.git/models"
	"git.kingpenguin.tk/chteufleur/datahouse.git/models/database"
	_ "git.kingpenguin.tk/chteufleur/datahouse.git/models/temperature"
	"git.kingpenguin.tk/chteufleur/datahouse.git/models/user"
	"git.kingpenguin.tk/chteufleur/datahouse.git/models/variables"
	_ "git.kingpenguin.tk/chteufleur/datahouse.git/routers"
	"git.kingpenguin.tk/chteufleur/datahouse.git/watchlog"
	"git.kingpenguin.tk/chteufleur/datahouse.git/xmpp"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/mattn/go-sqlite3"

	"time"
)

var (
	log = logs.NewLogger(10000)
)

func init() {
	log.SetLogger(variables.LogType, variables.LogParams)
	url := ""
	db := ""
	if database.DatabaseInstance == database.MySQL {
		// MySQL
		orm.RegisterDriver(database.MySQL, orm.DRMySQL)
		url = database.UserDB + ":" + database.PwdDB + "@/" + database.DataBase + "?charset=utf8"
		db = "mysql"
	} else {
		// SQLite
		orm.RegisterDriver(database.SQLITE, orm.DRSqlite)
		url = "datahouse.db"
		db = "sqlite3"
	}

	err := orm.RegisterDataBase(database.Alias, db, url)
	if err != nil {
		log.Error("Failed to register database", err)
	}

	force := false
	verbose := true
	err = orm.RunSyncdb(database.Alias, force, verbose)
	if err != nil {
		log.Error("Failed to initialize database", err)
	}
}

func main() {

	if !user.IsUserExist("admin") {
		user.AddUser("admin", "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918")
	}
	go reborn()

	time.Sleep(1 * time.Second)
	models.ChanRuns <- watchlog.EndRun
	time.Sleep(1 * time.Second)
	//	models.ChanRuns <- xmpp_manager.EndRun

	beego.Run()
}

func reborn() {
	for {
		action := <-models.ChanRuns

		switch action {
		case xmpp_manager.EndRun:
			go xmpp_manager.Run()
			log.Info("XMPP Started")

		case watchlog.EndRun:
			go watchlog.Run()
			log.Info("Watchlog Started")
		}
	}
}
