package de.duehl.swing.ui.menu.collection.tools;

/*
 * Copyright 2021 Christian Dühl. All rights reserved.
 *
 * This program is free software. You can redistribute it and/or
 * modify it under the same terms as perl:
 *
 * general:  http://dev.perl.org/licenses/
 * GPL:      http://dev.perl.org/licenses/gpl1.html
 * artistic: http://dev.perl.org/licenses/artistic.html
 */

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.duehl.basics.text.Text;

/**
 * Diese Hilfsklasse erzeugt eine lesbare Darstellung des KeyCodes eines Tastaturkommandos.
 *
 * @version 1.01     2021-04-21
 * @author Christian Dühl
 */

class ReadableKeyCodeGenerator {

    private static final Map<Integer, String> DESCRIPITON_BY_KEY_CODE =
            new KeyEventMapGenerator().generate().getDescriptionByKeyCode();

    private final int keyCode;

    public ReadableKeyCodeGenerator(int keyCode) {
        this.keyCode = keyCode;
    }

    public String generate() {
        if (DESCRIPITON_BY_KEY_CODE.containsKey(keyCode)) {
            return prepareKeyCodeDescription(DESCRIPITON_BY_KEY_CODE.get(keyCode));
        }
        else {
            return Integer.toString(keyCode);
        }
    }

    private String prepareKeyCodeDescription(String description) {
        String modifiedDescription = description;

        if (modifiedDescription.startsWith("VK_")) {
            modifiedDescription = modifiedDescription.substring("VK_".length());
        }

        modifiedDescription = modifiedDescription.replace("_", "-");

        if (modifiedDescription.startsWith("NUMPAD")) {
            modifiedDescription = modifiedDescription.substring("NUMPAD".length());
            modifiedDescription += " auf dem Nummernblock";
        }

        if (modifiedDescription.matches(Text.MIXED + "+")) {
            modifiedDescription = Text.toFirstUpperCase(modifiedDescription);
        }
        else if (modifiedDescription.matches(Text.MIXED + "+-" + Text.MIXED + "+")) {
            List<String> parts = Text.splitBy(modifiedDescription, "-");
            List<String> modifiedParts = new ArrayList<>();
            for (String part : parts) {
                String modifiedPart = Text.toFirstUpperCase(part);
                modifiedParts.add(modifiedPart);
            }
            modifiedDescription = Text.join("-", modifiedParts);
        }

        return modifiedDescription;
    }

}
