package rest;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import classes.Frequentation;

@Path("/")
@Produces("application/json")
public class RestService {

	private static Logger LOGGER = Logger.getLogger("jai.jaxrs");

	private static SimpleDateFormat sdf= new SimpleDateFormat("MMddyyyy");

	private static String messageBienvenue="Bienvenue à l'espace ";

	private static String messagePlusieursPassages="De nouveau bienvenue à l'espace ";

	@Path("/badge/{id}/{espace}")
	@GET
	public String validerBadge(@PathParam("id") String id, @PathParam("espace") String espace, @Context ServletContext context) {
		LOGGER.info("validation du badge " + id + " a l'espace " + espace);
		Map<String,String> mapPassageMicrofolies = (Map<String, String>) context.getAttribute("MapPassageMicrofolies");
		String stringVerifPassage = sdf.format(new Date())+ " " + espace;
		String messageRetour=messageBienvenue + espace;
		if(mapPassageMicrofolies==null) {
			mapPassageMicrofolies=new HashMap<String,String>();
			mapPassageMicrofolies.put(id, stringVerifPassage);
		}
		else {
			String listPassage = mapPassageMicrofolies.get(id);
			if(listPassage==null) {
				mapPassageMicrofolies.put(id,new Date().toString() + " " + espace);
			} else {
				if(!listPassage.contains(stringVerifPassage)){
					mapPassageMicrofolies.put(id,listPassage);
				} else {
					messageRetour=messagePlusieursPassages + espace;
				}
			}
		}	
		context.setAttribute("MapPassageMicrofolies", mapPassageMicrofolies);
		return messageRetour;
	}

	@Path("freq/{espace}/{from}/{to}")
	@GET
	public String frequence(@PathParam("espace") String espace, @PathParam("from") String from, @PathParam("to") String to, @Context ServletContext context) {
		try {
			Date begin = sdf.parse(from);
			Date end = sdf.parse(to);
			Pattern pattern = Pattern.compile(",");
			try (BufferedReader in = new BufferedReader(new FileReader(context.getRealPath("data/frequentation.csv")));) {
				List<Frequentation> frequentations = in .lines() .skip(1) .map(line -> { 
					String[] x = pattern.split(line); 
					try {
						return new Frequentation(x[0], x[1], x[2]);
					} catch (ParseException e) {
						e.printStackTrace();
					}
					return null; }) .collect(Collectors.toList());
				String toReturn = "{\"data\":[";
				for (Frequentation f : frequentations) {
					if(f.getDate().after(begin) && f.getDate().before(end))
					toReturn+=f.toString()+",";
				}
				toReturn=toReturn.substring(0,toReturn.length()-1) + "]}";
				return toReturn;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return "File not valid";
			} catch (IOException e) {
				e.printStackTrace();
				return "File not valid";
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
			return "Date not valid, format : MMddyyyy";
		}
	}

	@Path("profile/{id}")
	@GET
	public String profil(@PathParam("id")String id) {
		LOGGER.info("profil " +id);
		return "{\n\tid:" + id + "\n}";
	}

}
