package main

import (
	"bufio"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path"
)

var SubmissionDir string
var TmpSubmissionDir string

func saveTeamFile(p string, w http.ResponseWriter, r *http.Request) bool {
	if len(SubmissionDir) < 1 || len(p) < 1 {
		http.Error(w, "{\"errmsg\":\"Requête invalide.\"}", http.StatusBadRequest)
		return false
	} else if len(p) <= 0 {
		log.Println("EMPTY $EXERCICE RECEIVED:", p)
		http.Error(w, "{\"errmsg\":\"Internal server error. Please retry in few seconds.\"}", http.StatusInternalServerError)
		return false
	} else if _, err := os.Stat(path.Join(SubmissionDir, p)); !os.IsNotExist(err) {
		// Previous submission not treated
		http.Error(w, "{\"errmsg\":\"Du calme ! une requête est déjà en cours de traitement.\"}", http.StatusPaymentRequired)
		return false
	} else if err = saveFile(path.Join(SubmissionDir, p), r); err != nil {
		log.Println("Unable to handle submission file:", err)
		http.Error(w, "{\"errmsg\":\"Internal server error. Please retry in few seconds.\"}", http.StatusInternalServerError)
		return false
	}
	return true
}

func saveFile(p string, r *http.Request) error {
	dirname := path.Dir(p)
	if _, err := os.Stat(dirname); os.IsNotExist(err) {
		if err = os.MkdirAll(dirname, 0755); err != nil {
			return err
		}
	}

	// Write content to temp file
	tmpfile, err := ioutil.TempFile(TmpSubmissionDir, "")
	if err != nil {
		return err
	}

	writer := bufio.NewWriter(tmpfile)
	reader := bufio.NewReader(r.Body)
	if _, err = reader.WriteTo(writer); err != nil {
		return err
	}
	writer.Flush()
	tmpfile.Close()

	if err = os.Rename(tmpfile.Name(), p); err != nil {
		log.Println("[ERROR] Unable to move file: ", err)
		return err
	}

	return nil
}
