package leigh.notek.app.javafx;

import leigh.mecha.lang.StringAlternator;
import leigh.mecha.lang.Transformer;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.mecha.util.StringAccumulatorV2;

import java.util.ArrayList;

/**
 * Perform Notek-specific markdown transformations to enable functionality which is not present in ordinary
 * markdown. We convert our proprietary format into industry-standard markdown so that it can be rendered with
 * standard libraries.
 *
 * @author Alex Leigh
 */
public class NotekTransformer implements Transformer<String> {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(NotekTransformer.class);

    public String transform(String val) {
        StringAccumulatorV2 sa = new StringAccumulatorV2("");
        ArrayList<String> out = new ArrayList<>();

        StringAlternator.alternate(out, val);

        for (String str : out) {
            logger.debug("Processing token -->{}<--", str);
            if (str.startsWith("#")) {
                if (str.chars().filter(value -> value == '#').count() == str.length()) {
                    logger.trace("All hashes.");
                    sa.add(str);
                    continue;
                }

                String newTag = "[" + str + "](" + str + ")";
                sa.add(newTag);
            } else if (str.startsWith("[[") && str.endsWith("]]")) {
                String tag = str.substring(2, str.length() - 2);
                String newTag = "[" + tag + "](" + tag + ")";
                sa.add(newTag);
            } else {
                sa.add(str);
            }
        }

        logger.debug("Returning new string: {}", sa.asString());

        return sa.asString();
    }
}
