package main

import (
	"fmt"
	"net/http"
	"path"
	"strconv"
	"time"
)

func SubmissionHandler(w http.ResponseWriter, r *http.Request, team string, sURL []string) {
	if time.Now().Sub(challengeEnd) > 0 {
		http.Error(w, "{\"errmsg\":\"Vous ne pouvez plus soumettre, le challenge est terminé.\"}", http.StatusGone)
		return
	}

	if len(sURL) != 1 {
		http.Error(w, "{\"errmsg\":\"Arguments manquants.\"}", http.StatusBadRequest)
		return
	}

	// Check exercice validity then save the submission
	if pex, err := strconv.ParseInt(sURL[0], 10, 64); err != nil {
		http.Error(w, "{\"errmsg\":\"Requête invalide.\"}", http.StatusBadRequest)
		return
	} else if exercice := fmt.Sprintf("%d", pex); len(exercice) < 1 {
		http.Error(w, "{\"errmsg\":\"Requête invalide.\"}", http.StatusBadRequest)
		return
	} else if saveTeamFile(path.Join(team, exercice), w, r) {
		http.Error(w, "{\"errmsg\":\"Son traitement est en cours...\"}", http.StatusAccepted)
	}
}
