package controllers

import (
	"github.com/astaxie/beego"

	"git.kingpenguin.tk/chteufleur/datahouse.git/models/user"
	"git.kingpenguin.tk/chteufleur/datahouse.git/models/variables"
)

type LoginController struct {
	beego.Controller
}

func (c *LoginController) Prepare() {
}

func (c *LoginController) Get() {
	routeRedirect := c.Ctx.Input.Param(":route")

	sess := c.GetSession(variables.SessionName)
	if sess != nil {
		if routeRedirect == "" {
			c.Redirect(variables.UserRoute, 302)
		} else {
			c.Redirect("/"+routeRedirect, 302)
		}
		return
	}

	c.TplNames = "login.tpl"
}

func (c *LoginController) Post() {
	routeRedirect := c.Ctx.Input.Param(":route")

	sess := c.GetSession(variables.SessionName)
	if sess != nil {
		if routeRedirect == "" {
			c.Redirect(variables.RootRoute, 302)
		} else {
			c.Redirect("/"+routeRedirect, 302)
		}
		return
	}

	login := c.GetString("login")
	passwd := c.GetString("password")

	if !isLoginOK(login, passwd) {
		c.Abort("403")
	}

	c.SetSession(variables.SessionName, login)
	if routeRedirect == "" {
		c.Redirect(variables.UserRoute, 302)
	} else {
		c.Redirect("/"+routeRedirect, 302)
	}
}

func isLoginOK(lgn, pwd string) bool {
	ret := pwd != "" // Do not authorize empty password
	usr := user.GetUserByLogin(lgn)
	return ret && pwd == usr.Password
}
