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.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * Erzeugt ein Verzeichnis von Tastatur-Bezeichnern nach den in der Klasse KeyEvent definierten
 * Konstanten.
 *
 * Die Idee stammt von
 *     https://stackoverflow.com/questions/15313469/java-keyboard-keycodes-list/31637206
 * und wurde angepasst.
 *
 * @version 1.01     2021-04-21
 * @author Christian Dühl
 */

class KeyEventMapGenerator {

    private final Field[] fields;

    private final Map<Integer, String> descriptionByKeyCode;

    public KeyEventMapGenerator() {
        fields = java.awt.event.KeyEvent.class.getDeclaredFields();
        descriptionByKeyCode = new HashMap<>();
    }

    public KeyEventMapGenerator generate() {
        try {
            tryToGenerate();
        }
        catch (IllegalArgumentException | IllegalAccessException exception) {
            // Nichts weiter, aber Ende.
        }
        return this;
    }

    private void tryToGenerate() throws IllegalArgumentException, IllegalAccessException {
        for (Field field : fields) {
            tryToGenerate(field);
        }
    }

    private void tryToGenerate(Field field)
            throws IllegalArgumentException, IllegalAccessException {
        if (Modifier.isStatic(field.getModifiers())) {
            String name = field.getName();
            int value = field.getInt(name);
            descriptionByKeyCode.put(value, name);
        }
    }

    public Map<Integer, String> getDescriptionByKeyCode() {
        return descriptionByKeyCode;
    }

}
