package main

import (
	"log"
	"net/http"
	"path"
)

var allowRegistration bool = false

func RegistrationHandler(w http.ResponseWriter, r *http.Request, sURL []string) {
	if !allowRegistration {
		log.Printf("UNHANDLED %s registration request from %s: %s [%s]\n", r.Method, r.RemoteAddr, r.URL.Path, r.UserAgent())
		http.Error(w, "{\"errmsg\":\"L'enregistrement d'équipe n'est pas permis.\"}", http.StatusForbidden)
		return
	}

	if len(sURL) < 1 || len(sURL[0]) == 0 {
		http.Error(w, "{\"errmsg\":\"Arguments manquants.\"}", http.StatusBadRequest)
		return
	}
	teamInitialName := sURL[0]

	// Check request type and size
	if r.Method != "POST" {
		http.Error(w, "{\"errmsg\":\"Requête invalide.\"}", http.StatusBadRequest)
		return
	} else if r.ContentLength < 0 || r.ContentLength > 4095 {
		http.Error(w, "{\"errmsg\":\"Requête trop longue ou de taille inconnue\"}", http.StatusRequestEntityTooLarge)
		return
	}

	if err := saveFile(path.Join(SubmissionDir, "_registration", teamInitialName), r); err != nil {
		log.Println("Unable to open registration file:", err)
		http.Error(w, "{\"errmsg\":\"Internal server error. Please retry in few seconds.\"}", http.StatusInternalServerError)
	} else {
		// File enqueued for backend treatment
		http.Error(w, "{\"errmsg\":\"Demande d'enregistrement acceptée\"}", http.StatusAccepted)
	}
}
