package controllers

import (
	"errors"
	"net/http"

	"git.1248.nz/1248/Otfe/misc/cookie"
	"git.1248.nz/1248/Otfe/misc/helpers"
	"git.1248.nz/1248/Otfe/misc/rand"
	"git.1248.nz/1248/Otfe/models"
)

//Session controllers
type Session struct{}

type pageData struct {
	Title string
	Err   string
	User  models.User
}

//New login form
func (s *Session) New(w http.ResponseWriter, r *http.Request) {
	var err error
	data := pageData{Title: "Login"}
	data.Err, err = cookie.Read(r, "error")
	if err == nil {
		cookie.Delete(w, "error")
	}
	t(w, data, "/static/login.gtpl")
}

//Create a new session
func (s *Session) Create(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	//Get email and password and check they are not empty
	email := r.Form.Get("email")
	password := r.Form.Get("password")

	//Check if user exists
	var user models.User

	//Check password is correct
	if user.Read("email", email) == nil &&
		helpers.CheckPasswordHash(password, user.Password) == nil {
		id, _ := rand.B64String(32)
		sess := models.Session{ID: id, UserID: user.ID}
		sess.Create()
		cookie.Create(w, "session", sess.ID)
		http.Redirect(w, r, "/", http.StatusFound)
	} else {
		loginFail(w, r, errors.New("Email or password incorrect"))
	}
}

//Delete session
func (s *Session) Delete(w http.ResponseWriter, r *http.Request) {
	id, err := cookie.Read(r, "session")
	//Check user is logged in
	if err == nil {
		cookie.Delete(w, "session")
		var session models.Session
		session.Delete(id)
		http.Redirect(w, r, "/", http.StatusFound)
	}

}

func loginFail(w http.ResponseWriter, r *http.Request, err error) {
	cookie.Create(w, "error", err.Error())
	http.Redirect(w, r, "/login", http.StatusFound)
}