package org.etsi.mts.tdl.openapi2tdl.next.doc;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map.Entry;

import org.etsi.mts.tdl.openapi2tdl.next.OpenAPI2TDLTranslatorNext;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.PathItem.HttpMethod;

public class Doc {
	StringBuffer content = new StringBuffer();
	private OpenAPI model;

	public void append(String s) {
		content.append(s);
	}
	
	public static void main(String[] args) throws Exception {
		boolean validate = !(args.length >= 1 && args[0].equals("-n"));
		Doc doc = new Doc();
		doc.processModel(args[1], validate);
		Files.writeString(Path.of(args[1]+"-RQ-ICS-TSS.md"), doc.content);
	}
	public void processModel(String filename, boolean validate) throws Exception {
		
		model = OpenAPI2TDLTranslatorNext.parseSpec(filename, true);
//		processModel(model, Describe.init(model, content));
		append(String.format("== Model %s\n", filename));
		append("# Generated Documentation\n");

		processModel(model, new RQ().init(model, this));
		append("\n## Implementation Conformance Statements\n");

		processModel(model, new ICSDetail().init(model, this));
		processModel(model, new ICSMethod().init(model, this));
		processModel(model, new ICSPath().init(model, this));
		processModel(model, new ICSHierarchical().init(model, this));
		processModel(model, new TSS().init(model, this));

		append("------\n\n");
	}

	private static void processModel(OpenAPI model, OpenAPIVisitor visitor)  {
		visitor.preamble(model);
		for (Entry<String, PathItem> pathEntry : model.getPaths().entrySet()) {
			String path = pathEntry.getKey();
			PathItem pathItem = pathEntry.getValue();
			visitor.path(path);
			for (Entry<HttpMethod, Operation> o : pathItem.readOperationsMap().entrySet()) {
				visitor.operation(path, o.getKey().name(), o.getValue());
			}
		}
		visitor.postamble(model);

	}
	//convert to word with pandoc

	private static void getICSTemplate(OpenAPI model) {
		String level = "Template";
		System.out.printf("\n#### %s\n\n", level);

		String header = 
				"| ID | Resource  | Reference | Method | Type  | Request | Response |\n" + 
				"| -- | --------- | --------- | ------ | ----- | ------- | -------- |";
		String footer = 
				"[Table X.Y: Extracted ICS ("+level+")]{custom-style=\"FL\"}";
		System.out.println(header);

		for (Entry<String, PathItem> pathEntry : model.getPaths().entrySet()) {
			String path = pathEntry.getKey();
			PathItem pathItem = pathEntry.getValue();
			for (Entry<HttpMethod, Operation> op : pathItem.readOperationsMap().entrySet()) {
				for (String r : op.getValue().getResponses().keySet()) {
				}
			}
		}
		
		System.out.println(footer);
	}

	public StringBuffer getContent() {
		return content;
	}
	
}
