package com.bernard.greposimu.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bernard.greposimu.GrepoSimuApplication;
import com.bernard.greposimu.model.game.GameConfig;
import com.bernard.greposimu.model.simulator.Ville;
import com.bernard.greposimu.model.simulator.command.Command;
import com.bernard.greposimu.model.simulator.SimulatorData;
import com.bernard.greposimu.model.simulator.objective.TownObjective;
import com.bernard.greposimu.source.JSONSourcer;

@Controller
public class SchedulerController {

	Map<UUID,SimulatorData> registered = new HashMap<>();

	@CrossOrigin
    @PostMapping(value = "/registerScheduler", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
	//@GetMapping(value = "/registerScheduler")
	public @ResponseBody String register(Model model,@RequestBody String data) {
		//System.out.println(data.toString());
		GameConfig gc = GrepoSimuApplication.GREPOLIS_GC;
		SimulatorData sd = JSONSourcer.makeSimulationData(data.toString(),gc);

		UUID uuid = UUID.randomUUID();
		registered.put(uuid, sd);

        return uuid.toString();
	}

	@GetMapping(value = "/scheduler/{uuid}")
	public String simulator(Model model, @PathVariable("uuid") String uuidStr) {
		UUID uuid = UUID.fromString(uuidStr);
		
		GameConfig gc = GrepoSimuApplication.GREPOLIS_GC;
		SimulatorData sd = registered.get(uuid);

		TownObjective defObjective = GrepoSimuApplication.OBJECTIVES.get("defTerTown");
		defObjective.setGc(gc);

		StringBuilder out = new StringBuilder();
		for(Ville v : sd.getVilles().values()) {
			out.append("<h3>==== Ville "+v.getNom()+" ====</h3>\n");
			out.append(defObjective.getDifferences(v).stream().map(Command::toString).sorted().collect(Collectors.joining("<br/>\n")));
		}

        model.addAttribute("content",out.toString());
		return "debug";
	}

}
