package user

import (
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"

	"git.kingpenguin.tk/chteufleur/datahouse.git/models/database"
	"git.kingpenguin.tk/chteufleur/datahouse.git/models/utils"
)

type User struct {
	Id       int64
	Login    string
	Password string
}

func init() {
	// register model
	orm.RegisterModel(new(User))
}

func IsUserExist(login string) bool {
	o := orm.NewOrm()
	o.Using(database.Alias)

	ret := false
	var maps []orm.Params
	_, err := o.QueryTable(new(User)).Filter("Login", login).Values(&maps)
	if err == nil {
		for _, _ = range maps {
			ret = true
			break
		}
	}
	return ret
}

func GetUserByLogin(login string) *User {
	o := orm.NewOrm()
	o.Using(database.Alias)

	ret := new(User)
	var maps []orm.Params
	_, err := o.QueryTable(new(User)).Filter("Login", login).Values(&maps)
	if err == nil {
		for _, m := range maps {
			ret.Id = utils.GetInt(m, "Id")
			ret.Login = utils.GetString(m, "Login")
			ret.Password = utils.GetString(m, "Password")
			break
		}
	}
	return ret
}

func GetUser(id int64) *User {
	o := orm.NewOrm()
	o.Using(database.Alias)

	ret := new(User)
	var maps []orm.Params
	_, err := o.QueryTable(new(User)).Filter("Id", id).Values(&maps)
	if err == nil {
		for _, m := range maps {
			ret.Id = utils.GetInt(m, "Id")
			ret.Login = utils.GetString(m, "Login")
			ret.Password = utils.GetString(m, "Password")
			break
		}
	}
	return ret
}

func AddUser(login, sha256Pass string) {
	o := orm.NewOrm()
	o.Using(database.Alias)

	_, _ = o.Insert(&User{Login: login, Password: sha256Pass})
}

func ChangePassword(login, newPwd string) {
	o := orm.NewOrm()
	o.Using(database.Alias)

	user := GetUserByLogin(login)
	if o.Read(user) == nil {
		user.Password = newPwd
		o.Update(user)
	}
}
