/*
  This file is a part of Angry IP Scanner source code,
  see http://www.angryip.org/ for more information.
  Licensed under GPLv2.
 */
package net.azib.ipscan.exporters;

import net.azib.ipscan.config.Version;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * XMLExporter
 *
 * @author Anton Keks
 */
public class XMLExporter extends AbstractExporter {
	static final String ENCODING = "UTF-8";

	public XMLExporter() {}

	private int ipFetcherIndex;
	private String[] fetcherNames;
	
	public String getId() {
		return "exporter.xml";
	}

	public String getFilenameExtension() {
		return "xml";
	}

	@Override
	public void shouldAppendTo(File file) {
		// TODO: allow appending: use RandomAccessFile here to remove the closing tag before appending
		throw new ExporterException("xml.noAppend");
	}

	@Override
	public void start(OutputStream outputStream, String feederInfo) throws IOException {
		output = new PrintWriter(new OutputStreamWriter(outputStream, ENCODING));
		output.println("<?xml version=\"1.0\" encoding=\"" + ENCODING + "\" standalone=\"yes\"?>");
		output.println("<!-- This file has been generated by " + Version.getFullName() + " -->");
		output.println("<!-- Visit the website at " + Version.WEBSITE + " -->");

		var dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		output.println("<scanning_report time=\"" + LocalDateTime.now().format(dtf) + "\">");
		
		// this is a hack to extract feeder name from the feederInfo
		// this may not work with some non-standard feeders
		var colonPos = feederInfo.indexOf(':');
		String feederName = null;
		if (colonPos >= 0) {
			feederName = feederInfo.substring(0, colonPos);
			feederInfo = feederInfo.substring(colonPos + 1);
		}
		output.print("\t<feeder" + (feederName != null ? " name=\"" + feederName.trim() +"\"" : "") + ">");
		output.print("<![CDATA[" + feederInfo.trim() + "]]>");
		output.println("</feeder>");
		
		output.println("\t<hosts>");
	}

	@Override
	public void end() throws IOException {
		output.println("\t</hosts>");
		output.println("</scanning_report>");
		if (output.checkError()) {
			throw new IOException();
		}
	}

	public void setFetchers(String[] fetcherNames) throws IOException {
		ipFetcherIndex = IPListExporter.findFetcherById("fetcher.ip", fetcherNames);
		this.fetcherNames = fetcherNames;
	}

	public void nextAddressResults(Object[] results) throws IOException {
		output.println("\t\t<host address=\"" + results[ipFetcherIndex] + "\">");
		
		for (var i = 0; i < results.length; i++) {
			if (results[i] != null) {
				output.println("\t\t\t<result name=\"" + fetcherNames[i] + "\"><![CDATA[" + results[i] + "]]></result>");
			}
		}
		
		output.println("\t\t</host>");
	}
}
