/*
 * Copyright 2020 ETSI
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution.
 * 3. Neither the name of the copyright holder nor the names of its contributors 
 *    may be used to endorse or promote products derived from this software without 
 *    specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package fr.mines_stetienne.ci.saref.managers;

import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;

import fr.mines_stetienne.ci.saref.Main;

import org.apache.commons.io.IOUtils;
import org.eclipse.jgit.util.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class GenerateRDFaManager {

	public static void GenerateRDFa(String categoryChanger, String repoName, String href, File CSV, File HTML,
			String identifier) {
		String row = "";

		try (FileWriter htmlWriter = new FileWriter(HTML);
				BufferedReader csvReader = new BufferedReader(new FileReader(CSV));) {
			String header = IOUtils.toString(Main.class.getClassLoader().getResourceAsStream("themis/header.html"),
					StandardCharsets.UTF_8);
			String body = IOUtils.toString(Main.class.getClassLoader().getResourceAsStream("themis/body.html"),
					StandardCharsets.UTF_8);
			String footer = IOUtils.toString(Main.class.getClassLoader().getResourceAsStream("themis/footer.html"),
					StandardCharsets.UTF_8);

			header = header.replaceAll("@ontologyName", repoName).replaceAll("@href", href + identifier + "#");

			body = body.replaceAll("@docType", StringUtils.capitalize(identifier)).replaceAll("@ontologyName",
					repoName);

			htmlWriter.write(header);
			htmlWriter.write(body);

			List<String[]> allData = readDataFromCustomSeperator(CSV);

			if (identifier.equals("requirements")) {
				for (String[] data : allData) {
					if (data[1].equals("Category")) {
						continue;
					} else {
						if (categoryChanger.equals("") || categoryChanger.equals(data[1])
								|| !data[1].equals("Category")) {
							if (!categoryChanger.equals(data[1]) && !categoryChanger.equals("Category")) {
								if (categoryChanger.equals("")) {
									categoryChanger = data[1];
								} else {
									categoryChanger = data[1];
									String endTableData = "</table> \n" + "\n" + "<p>\n" + "</p>\n" + "\n";
									htmlWriter.write(endTableData);
								}
								categoryChanger = data[1];
								String entrytoTable2 = "<table align=\"center\" border=\"1\"  prefix=\"vtc: https://w3id.org/def/vtc#\">\n";
								htmlWriter.write(entrytoTable2);
								String category = "<caption>Requirements for the \"" + categoryChanger
										+ "\" category</caption>\n";
								htmlWriter.write(category);

								String entry = "<tr>\n" + "    <th>Id</th>\n" + "    <th>Requirement</th>\n"
										+ "  </tr>\n" + "\n" + "<tr id=\"" + data[0] + "\" resource=\"requirement/"
										+ data[0] + "\" typeof=\"vtc:Requirement\" property=\"vtc:category\" content=\""
										+ data[1] + "\">\n" + "    <td property=\"vtc:requirementId\">" + data[0]
										+ "</td>\n" + "    <td property=\"dc:description\">" + data[2] + "</td>\n"
										+ "  </tr>\n" + "\n";
								htmlWriter.write(entry);
							} else {
								categoryChanger = data[1];

								String entry = "<tr id=\"" + data[0] + "\" resource=\"requirement/" + data[0]
										+ "\" typeof=\"vtc:Requirement\" property=\"vtc:category\" content=\"" + data[1]
										+ "\">\n" + "    <td property=\"vtc:requirementId\">" + data[0] + "</td>\n"
										+ "    <td property=\"dc:description\">" + data[2] + "</td>\n" + "  </tr>\n"
										+ "\n";
								htmlWriter.write(entry);
							}
						}

					}
				}

			} else {
				for (String[] data : allData) {
					if (data[2].equals("Category")) {
						continue;
					} else {
						if (categoryChanger.equals("") || categoryChanger.equals(data[2])
								|| !data[2].equals("Category")) {

							if (!categoryChanger.equals(data[2]) && !categoryChanger.equals("Category")) {
								if (categoryChanger.equals("")) {
									categoryChanger = data[2];
								} else {
									categoryChanger = data[2];
									String endTableData2 = "</table> \n" + "\n" + "<p>\n" + "</p>\n" + "\n";
									htmlWriter.write(endTableData2);
								}

								categoryChanger = data[2];
								String entrytoTable2 = "<table align=\"center\" border=\"1\"  prefix=\"vtc: https://w3id.org/def/vtc#\">\n";
								htmlWriter.write(entrytoTable2);
								String category = "<caption>Tests for the \"" + categoryChanger
										+ "\" category</caption>\n";
								htmlWriter.write(category);
								if (!data[1].isEmpty()) {
									String entry = "<tr>\n" + "    <th>Id</th>\n" + "    <th>Requirement</th>\n"
											+ "    <th>Test</th>\n" + "  </tr>\n" + "\n" + "<tr id=\"" + data[1]
											+ "\" resource=\"testCaseDesign/" + data[0]
											+ "\" typeof=\"vtc:TestCaseDesign\">\n" + "    <td property=\"vtc:testId\">"
											+ data[0] + "</td>\n"
											+ "    <td><span property=\"vtc:comesFromRequirement\" href=\"requirement/"
											+ data[1] + "\"><a href=\"requirements.html#" + data[1] + "\">"
											+ data[1] + "</a></span></td>\n"
											+ "    <td property=\"vtc:desiredBehaviour\">" + data[3] + "</td>\n"
											+ "  </tr>\n" + "\n";
									htmlWriter.write(entry);
								} else {
									String entry = "<tr>\n" + "    <th>Id</th>\n" + "    <th>Test</th>\n" + "  </tr>\n"
											+ "\n" + "<tr resource=\"testCaseDesign/" + data[0]
											+ "\" typeof=\"vtc:TestCaseDesign\">\n" + "    <td property=\"vtc:testId\">"
											+ data[0] + "</td>\n" + "    <td property=\"vtc:desiredBehaviour\">"
											+ data[3] + "</td>\n" + "  </tr>\n" + "\n";
									htmlWriter.write(entry);
								}
							} else {
								categoryChanger = data[2];

								String entry = "<tr resource=\"testCaseDesign/" + data[0]
										+ "\" typeof=\"vtc:TestCaseDesign\">\n" + "    <td property=\"vtc:testId\">"
										+ data[0] + "</td>\n"
										+ "    <td><span property=\"vtc:comesFromRequirement\" href=\"requirement/"
										+ data[1] + "\"><a href=\"requirements.html#" + data[1] + "\">"
										+ data[1] + "</a></span></td>\n" + "    <td property=\"vtc:desiredBehaviour\">"
										+ data[3] + "</td>\n" + "  </tr>\n" + "\n";
								htmlWriter.write(entry);
							}
						}

					}
				}
			}

			String endTableData = "</table> \n" + "\n" + "<p>\n" + "</p>\n" + "\n";
			htmlWriter.write(endTableData);

			htmlWriter.write(footer);

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static List<String[]> readDataFromCustomSeperator(File file) {
		CSVParser parser = new CSVParserBuilder().withSeparator(';').withQuoteChar('"').build();

		try (FileReader filereader = new FileReader(file);
				CSVReader csvReader = new CSVReaderBuilder(filereader).withCSVParser(parser).build();) {

			// Read all data at once
			List<String[]> allData = csvReader.readAll();
			return allData;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
