package CipherCracker;

import it.unimi.dsi.fastutil.ints.IntList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ConverterHelpers {
    // 1. Change the Map keys to Character
    public static Map<Character, Integer> identifierMap = new HashMap<>();

    // 2. Change the Reverse Map to use Integer as the key and Character as the value
    public static Map<Integer, Character> reverseIdentifierMap = new HashMap<>();

    public static void mapBuilder() {
        for (int i = 0; i < 26; i++) {
            char lower = (char) ('a' + i);
            char upper = (char) ('A' + i);

            // Store using Character keys
            identifierMap.put(lower, i);
            identifierMap.put(upper, i);

            // Map the Integer back to a Character
            reverseIdentifierMap.put(i, lower);
        }
    }

    // String to integer arraylist converter
    public static ArrayList<Integer> primaryIdentifierConverter(String word) {
        if (word == null) {
            return new ArrayList<>();
        }

        int wordLength = word.length();
        ArrayList<Integer> convertedList = new ArrayList<>();

        for (int i = 0; i < wordLength; i++) {
            char currentCharacter = word.charAt(i);
            Integer mappedValue = identifierMap.get(currentCharacter);

            // This correctly guards against symbols/numbers by ignoring them
            if (mappedValue != null) {
                convertedList.add(mappedValue);
            }
        }
        return convertedList;
    }

    // integer arraylist to string converter
    public static String reversePrimaryIdentifierConverter(IntList encodedChars) {
        if (encodedChars == null) {
            return "";
        }

        int listLength = encodedChars.size();
        StringBuilder word = new StringBuilder();

        for (int i = 0; i < listLength; i++) {
            int identifier = encodedChars.getInt(i);
            Character mappedChar = reverseIdentifierMap.get(identifier);

            if (mappedChar != null) {
                word.append(mappedChar);
            }
        }
        return word.toString();
    }
}