package main

import (
	"encoding/base64"
	"encoding/binary"
	"encoding/json"
	"io/ioutil"
	"log"
	"math/rand"
	"os"

	"srs.epita.fr/fic-server/libfic"
)

var canResetProgression = false

type askResetProgress struct {
	ExerciceId int64 `json:"eid"`
}

func treatResetProgress(pathname string, team *fic.Team) {
	if !canResetProgression {
		log.Printf("[!!!] Receive reset_progress, whereas desactivated in settings.\n")
		return
	}

	// Generate a unique identifier to follow the request in logs
	bid := make([]byte, 5)
	binary.LittleEndian.PutUint32(bid, rand.Uint32())
	id := "[" + base64.StdEncoding.EncodeToString(bid) + "]"
	log.Println(id, "New ResetProgress receive", pathname)

	var ask askResetProgress

	if cnt_raw, err := ioutil.ReadFile(pathname); err != nil {
		log.Printf("%s [ERR] %s\n", id, err)
	} else if err = json.Unmarshal(cnt_raw, &ask); err != nil {
		log.Printf("%s [ERR] %s\n", id, err)
	} else if ask.ExerciceId == 0 {
		log.Printf("%s [WRN] Invalid content in reset_progress file: %s\n", id, pathname)
		os.Remove(pathname)
	} else if exercice, err := fic.GetExercice(ask.ExerciceId); err != nil {
		log.Printf("%s [ERR] Unable to retrieve the given exercice: %s\n", id, err)
	} else if exercice.Disabled {
		log.Println("[!!!] The team submits something for a disabled exercice")
	} else if err := team.ResetProgressionOnExercice(exercice); err != nil {
		log.Printf("%s [ERR] Unable to reset progression: %s\n", id, err)
	} else {
		appendGenQueue(fic.GenStruct{Id: id, Type: fic.GenTeam, TeamId: team.Id})
		if err = os.Remove(pathname); err != nil {
			log.Printf("%s [ERR] %s\n", id, err)
		}
	}
}
