package org.etsi.mts.tdl.openapi2tdl.next.doc;

import java.util.List;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.openapitools.codegen.utils.ModelUtils;

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;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.responses.ApiResponse;

public class ICSPath extends OpenAPIVisitor  {
	int ri = 0;
	private String level = "Path";

	@Override
	public void preamble(OpenAPI model) {
		content.append(String.format("\n#### %s\n\n", level));

		String header = 
				"| ID | Resource  | Reference | Method | Type  | Request | Response |\n" + 
				"| -- | --------- | --------- | ------ | ----- | ------- | -------- |\n";
		content.append(header);
	}

	@Override
	public void path(String path) {
		String cleanPath = path
				.replaceAll("/", "")
				.replaceAll("[\\{\\}]", "_")
				.replaceAll("_$", "");
		ri++;
		String pid = "P"+ri;
		
		String type = "M";
		String resource = path;
		String request = "(fill in request)";
		PathItem pathItem = model.getPaths().get(path);

		List<String> ops = pathItem.readOperationsMap().keySet().stream()
				.map(e -> e.name())
				.collect(Collectors.toList());
		
		List<String> opIds = pathItem.readOperationsMap().values().stream()
			.map(e -> e.getOperationId())
			.collect(Collectors.toList());

		List<String> allResponses = pathItem.readOperationsMap().values().stream()
				.flatMap(e -> e.getResponses().keySet().stream())
				.collect(Collectors.toList());
		
		String id = pid;
		String methods = String.join(",", ops);
		String pathReference = "Path: "+path + " : "+String.join(",", opIds);
		
		content.append(String.format(
				"| " + id
				+ " | " + resource
				+ " | " + pathReference
				+ " | " + methods
				+ " | " + type
				+ " | " + request
				+ " | " + String.join(",", allResponses)
				+ " |\n"));
	}

	@Override
	public void postamble(OpenAPI model) {
		String footer =
				"\n[Table X.Y: Extracted ICS ("+level+")]{custom-style=\"FL\"}\n";
		content.append(footer);
	}
}
