/*
 * Copyright 2012-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.internal.asciidoctor;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.asciidoctor.ast.Document;
import org.asciidoctor.extension.Preprocessor;
import org.asciidoctor.extension.PreprocessorReader;

// taken from https://github.com/hibernate/hibernate-asciidoctor-extensions/blob/1.0.3.Final/src/main/java/org/hibernate/infra/asciidoctor/extensions/savepreprocessed/SavePreprocessedOutputPreprocessor.java
/**
 * Preprocessor used to save the preprocessed output of the asciidoctor conversion. It allows to generate a single file
 * integrating all the includes.
 *
 * @author Guillaume Smet
 */
class CoalescerPreprocessor extends Preprocessor {

	private final File outputFile;

	private static final List<String> FILTER_LICENSE_MARKERS = Arrays.asList("[preface]", "<<<");

	private static final String COMMENT_MARKER = "//";

	private static final String SOURCE_MARKER = "[source";

	private static final List<String> SECTION_MARKERS = Arrays.asList("----", "....");

	private static final String HEADER = "////\n" + "DO NOT EDIT THIS FILE. IT WAS GENERATED.\n"
			+ "Manual changes to this file will be lost when it is generated again.\n"
			+ "Edit the files in the src/main/asciidoc/ directory instead.\n" + "////\n\n";

	CoalescerPreprocessor(File output_file) {
		outputFile = output_file;
	}

	@Override
	public void process(Document document, PreprocessorReader preprocessorReader) {
		try {
			LinkedList<String> filteredLines = filterLines(preprocessorReader.readLines());
			filteredLines.addFirst(HEADER);
			Files.write(outputFile.toPath(), filteredLines);
		}
		catch (IOException e) {
			throw new IllegalStateException("Unable to write the preprocessed file " + outputFile, e);
		}
	}

	/**
	 * This is used to filter out the license headers that are just after the markers
	 * defined. It also reindents the source code with spaces to be consistent with the
	 * 1.1 spec.
	 */
	private LinkedList<String> filterLines(List<String> lines) {
		LinkedList<String> filteredLines = new LinkedList<>();
		ParsingState state = ParsingState.NORMAL;
		int counter = 0;
		for (String line : lines) {
			counter++;
			switch (state) {
			case NORMAL:
				if (FILTER_LICENSE_MARKERS.contains(line)) {
					state = ParsingState.FILTER_LICENSE;
				}
				else if (line.startsWith(SOURCE_MARKER)) {
					state = ParsingState.SOURCE;
				}
				break;
			case SOURCE:
				if (SECTION_MARKERS.contains(line)) {
					state = ParsingState.SOURCE_CONTENT;
				}
				else {
					System.err.println("[source] requires to be followed by a section marker and line number [" + counter + "] with content [" + line + "] doesn't have it");
				}
				break;
			case SOURCE_CONTENT:
				if (SECTION_MARKERS.contains(line)) {
					state = ParsingState.NORMAL;
				}
				else {
					filteredLines.add(line.replaceAll("\t", "    "));
					continue;
				}
				break;
			case FILTER_LICENSE:
				if (line.startsWith(COMMENT_MARKER)) {
					continue;
				}
				else {
					state = ParsingState.NORMAL;
				}
				break;
			}
			filteredLines.add(line);
		}
		return filteredLines;
	}

	private enum ParsingState {

		NORMAL, FILTER_LICENSE, SOURCE, SOURCE_CONTENT,

	}

}
