package controllers

import (
	"github.com/astaxie/beego"

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

	"net/http"
)

type LoginController struct {
	beego.Controller
}

const (
	UrlXmppAuth = "http://auth.xmpp.kingpenguin.tk/auth"
)

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.TplName = "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 := false
	usr := user.GetUserByLogin(lgn)
	if usr.Id == 0 {
		return ret
	}

	log.Info("Standard auth")
	ret = pwd != "" && pwd == usr.Password

	if !ret && usr.JID != "" {
		log.Info("Auth by JID")
		resp, _ := http.Get(UrlXmppAuth + "?domain=datahouse.kingpenguin.tk&method=POST&jid=" + usr.JID + "&transaction_id=datahouse")
		httpStatusCode := resp.StatusCode
		if resp != nil && httpStatusCode == 200 {
			ret = true
		} else {
			ret = false
		}
	}
	return ret
}
