/**
 * 
 */
package org.etsi.saref.server.resources;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.ServerErrorException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.etsi.saref.server.outputformatter.TestCase;
import org.etsi.saref.server.outputformatter.TestSuite;
import org.glassfish.jersey.server.mvc.Template;

/**
 * @author Omar Qawasmeh
 *
 * 
 */
@Path("/report.html")
public class Report {

	@GET
	@Produces(MediaType.TEXT_HTML)
	@Template(name = "/report")
	public TestSuite fillReportPage(@QueryParam("q") String url)
			throws WebApplicationException, JAXBException, IOException {
		// url=getRedirectedLink(url).replaceAll("https://gitlab.emse.fr/saref/",
		// "http://saref.gitlab.emse.fr/-/");
		// url=url.replaceAll("/file/", "/");
		System.out.println("omaaar .... " + url);
		// To access the repository
		// https://gitlab.emse.fr/saref/saref4abcd/-/jobs/artifacts/master/browse?job=checkshacl

		// To access the xml file directly
		// https://gitlab.emse.fr/saref/saref4abcd/-/jobs/artifacts/master/file/report_output.xml?job=checkshacl
		JAXBContext jaxbContext;
		jaxbContext = JAXBContext.newInstance(TestSuite.class);
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		TestSuite tstSuite = (TestSuite) jaxbUnmarshaller.unmarshal(new URL(url));
		TestCase[] tstCase = tstSuite.getTestcase();
		for (int i = 0; i < tstCase.length; i++) {
			tstCase[i].setStatusFlag(tstCase[i].getStatus());
		}
		return tstSuite;
	}

	@POST
	@Produces(MediaType.TEXT_HTML)
	@Consumes(MediaType.APPLICATION_XML)
	@Template(name = "/report")
	public TestSuite fillReportPageForPost(TestSuite tstSuite)
			throws WebApplicationException, JAXBException, IOException {
		if(tstSuite == null) {
			throw new ServerErrorException(Status.BAD_REQUEST);
		}
		TestCase[] tstCase = tstSuite.getTestcase();
		for (int i = 0; i < tstCase.length; i++) {
			tstCase[i].setStatusFlag(tstCase[i].getStatus());
		}
		return tstSuite;
	}

	public static String getRedirectedLink(String URL) throws MalformedURLException, IOException {
		String url = URL;
		java.net.HttpURLConnection con = (java.net.HttpURLConnection) new java.net.URL(url).openConnection();
		con.setInstanceFollowRedirects(false);
		con.connect();
		String realURL = con.getHeaderField("Location");
		System.out.println(realURL);

		return realURL;

	}
}
