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

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

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
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));
		// .unmarshal(new
		// URL("http://saref.gitlab.emse.fr/-/saref4abcd/-/jobs/5654/artifacts/report_output.xml"));
		System.out.println(tstSuite.getDisabled());
		System.out.println(tstSuite.getTime());

		// System.out.println(tstSuite.getTestcase());
		TestCase[] tstCase = tstSuite.getTestcase();

		for (int i = 0; i < tstCase.length; i++) {

			System.out.println(tstCase[i].getStatus());

			tstCase[i].setStatusFlag(tstCase[i].getStatus());

			System.out.println("Status Flag\t\t" + tstCase[i].getStatusFlag());

			// System.out.println("Status\t" + tstCase[i].getStatus());
			// System.out.println("Name\t" + tstCase[i].getName());
			// System.out.println("System Error\t" + tstCase[i].getSystemErr());
			// System.out.println("System Error\t" + tstCase[i].getSystemOut());
		}

		// ReportResults reportResults= new ReportResults();

		// reportResults.report="asdqwe123";
		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;

	}
}
