package handlers

import (
	"html/template"
	"net/http"

	"192.168.1.180/odonax/filehost-athome/auth"
	"192.168.1.180/odonax/filehost-athome/config"
)

var Cfg *config.Config
var CfgPath string

func Setup(tmpl *template.Template) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if !auth.NeedsSetup(Cfg.AdminUser) {
			http.Redirect(w, r, "/", http.StatusSeeOther)
			return
		}

		if r.Method == "GET" {
			tmpl.Execute(w, nil)
			return
		}

		username := r.FormValue("username")
		password := r.FormValue("password")
		confirm := r.FormValue("confirm")

		if username == "" || password == "" {
			tmpl.Execute(w, map[string]string{"Error": "Please fill in all fields."})
			return
		}

		if password != confirm {
			tmpl.Execute(w, map[string]string{"Error": "Passwords do not match."})
			return
		}

		hash, err := auth.HashPassword(password)
		if err != nil {
			tmpl.Execute(w, map[string]string{"Error": "Something went wrong. Refresh the page and try again. If the issue persists, contact the developer of this application and tell them what happened."})
			return
		}

		Cfg.AdminUser = username
		Cfg.AdminPasswordHash = hash
		config.Save(CfgPath, *Cfg)

		http.Redirect(w, r, "/admin", http.StatusSeeOther)
	}
}

func Login(tmpl *template.Template) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if auth.NeedsSetup(Cfg.AdminUser) {
			http.Redirect(w, r, "/setup", http.StatusSeeOther)
			return
		}

		if r.Method == "GET" {
			tmpl.Execute(w, map[string]string{"SiteName": Cfg.SiteName})
			return
		}

		username := r.FormValue("username")
		password := r.FormValue("password")

		if username != Cfg.AdminUser || !auth.CheckPassword(Cfg.AdminPasswordHash, password) {
			tmpl.Execute(w, map[string]string{
				"SiteName": Cfg.SiteName,
				"Error":    "Invalid credentials.",
			})
			return
		}

		token, err := auth.GenerateSession()
		if err != nil {
			tmpl.Execute(w, map[string]string{
				"SiteName": Cfg.SiteName,
				"Error":    "Something went wrong. Please try again.",
			})
			return
		}
		auth.SetSessionCookie(w, token)
		http.Redirect(w, r, "/admin", http.StatusSeeOther)
	}
}

func Logout() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		auth.ClearSession(w, r)
		http.Redirect(w, r, "/", http.StatusSeeOther)
	}
}
