package main

import (
	json2 "encoding/json"
	"net/http"
	"time"

	"golang.org/x/crypto/bcrypt"
)

func HttpHandleUserNewToken(response http.ResponseWriter, request *http.Request) {
	if !HttpMethodAllowed(&response, request) {
		return
	}

	username := request.FormValue("username")
	if len(username) < 4 {
		http.Error(response, "no or short username", http.StatusBadRequest)
		return
	}

	password := request.FormValue("password")

	if len(password) < 8 {
		http.Error(response, "no or short password", http.StatusBadRequest)
		return
	}

	var (
		user *User
		err  error
		ctx  = request.Context()
	)

	user, err = CacheGetUserByName(username)
	if err != nil {
		user = &User{Name: username}
		if err = DbUserGetStandardInfoByName(ctx, user); err != nil {
			http.Error(response, "bad login", http.StatusUnauthorized)
			return
		}
		if err = DbGetWholeUser(ctx, user); err != nil {
			http.Error(response, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password))
	if err != nil {
		http.Error(response, "bad login", http.StatusUnauthorized)
		return
	}

	token, err := TokenCreate(user.Id)
	if err != nil {
		http.Error(response, "internal server error2", http.StatusInternalServerError)
		return
	}

	json, err := json2.Marshal(LoginReturn{Token: token, UserId: user.Id})
	if err != nil {
		http.Error(response, "internal server error3", http.StatusInternalServerError)
		return
	}

	response.WriteHeader(http.StatusCreated)
	response.Write(json)
}

func HttpHandleUserNew(response http.ResponseWriter, request *http.Request) {
	if !HttpMethodAllowed(&response, request) {
		return
	}

	username := request.FormValue("username")
	if len(username) < 4 {
		http.Error(response, "no or short username", http.StatusBadRequest)
		return
	}

	password := request.FormValue("password")
	if len(password) < 8 {
		http.Error(response, "no or short password", http.StatusBadRequest)
		return
	}

	color, err := ConvertStringToRgb(request.FormValue("color"))
	if err != nil {
		http.Error(response, "bad color", http.StatusBadRequest)
		return
	}

	hashedPassword, err := PasswordHash(password)
	if err != nil {
		http.Error(response, "internal server error", http.StatusInternalServerError)
		return
	}

	newUser := &User{
		Name:         username,
		PasswordHash: hashedPassword,
		Color:        color,
		CreatedAt:    time.Now(),
	}

	ctx := request.Context()

	err = DbUserSave(ctx, newUser)
	if err != nil {
		http.Error(response, "name taken", http.StatusUnauthorized)
		return
	}

	response.WriteHeader(http.StatusCreated)
}

func HttpHandleUserDelete(response http.ResponseWriter, request *http.Request) {
	if !HttpMethodAllowed(&response, request) {
		return
	}
	ctx := request.Context()

	userId, err := TokenValidateGetId(request.FormValue("token"))
	if err != nil {
		http.Error(response, "invalid token", http.StatusUnauthorized)
		return
	}

	err = DbUserDelete(ctx, userId)
	if err != nil {
		http.Error(response, "internal server error", http.StatusInternalServerError)
		return
	}

	CacheDeleteUser(userId)
	response.WriteHeader(http.StatusAccepted)
}

// HttpHandleUserModifyAppearance currently just color
func HttpHandleUserModifyAppearance(response http.ResponseWriter, request *http.Request) {
	if !HttpMethodAllowed(&response, request) {
		return
	}

	ctx := request.Context()
	user, err := GetUserByToken(ctx, request.FormValue("token"))
	if err != nil {
		http.Error(response, "invalid token", http.StatusUnauthorized)
		return
	}

	color, err := ConvertStringToRgb(request.FormValue("color"))
	if err != nil {
		http.Error(response, "invalid color", http.StatusBadRequest)
		return
	}
	user.Color = color
	err = DbUserSetColor(ctx, user)
	if err != nil {
		http.Error(response, "internal server error", http.StatusInternalServerError)
		return
	}
	response.WriteHeader(http.StatusAccepted)
}

// HttpHandleUserModifyAbout currently just pronouns
func HttpHandleUserModifyAbout(response http.ResponseWriter, request *http.Request) {
	if !HttpMethodAllowed(&response, request) {
		return
	}

	ctx := request.Context()
	user, err := GetUserByToken(ctx, request.FormValue("token"))
	if err != nil {
		http.Error(response, "invalid token", http.StatusUnauthorized)
		return
	}

	pronouns := request.FormValue("pronouns")
	if len(pronouns) > 25 || len(pronouns) < 2 {
		http.Error(response, "invalid pronouns", http.StatusBadRequest)
		return
	}

	user.Pronouns = pronouns
	err = DbUserSetPronouns(ctx, user)
	if err != nil {
		http.Error(response, "internal server error", http.StatusInternalServerError)
		return
	}
	response.WriteHeader(http.StatusAccepted)
}
