package io.ljunggren.csv.parser.utils;

import io.ljunggren.csv.parser.exception.CsvParseException;

/**
 * Utility helpers used by the CSV parser.
 *
 * <p>This class is not instantiable.</p>
 */
public final class ParserUtils {

    private ParserUtils() {
        throw new AssertionError("ParserUtils is a utility class and must not be instantiated");
    }

    /**
     * Convert a column reference to a zero-based column index.
     *
     * <p>Two notations are accepted:</p>
     * <ul>
     *   <li>An Excel-style alphabetic reference, e.g. {@code "A"} -&gt; {@code 0},
     *       {@code "Z"} -&gt; {@code 25}, {@code "AA"} -&gt; {@code 26}.</li>
     *   <li>A numeric string treated as an already-resolved zero-based index,
     *       e.g. {@code "0"} -&gt; {@code 0}, {@code "1"} -&gt; {@code 1}.</li>
     * </ul>
     *
     * @param column the column reference; must be non-null and alphanumeric
     * @return the zero-based column index
     * @throws CsvParseException if {@code column} is null or contains non-alphanumeric characters
     */
    public static int columnToInt(String column) {
        if (column == null || !column.matches("[a-zA-Z0-9]+")) {
            throw new CsvParseException(
                    String.format("Column must be alphanumeric. Actual: %s", column));
        }
        if (column.matches("[0-9]+")) {
            return Integer.parseInt(column);
        }
        String upper = column.toUpperCase();
        int index = 0;
        for (int i = 0; i < upper.length(); i++) {
            index *= 26;
            index += upper.charAt(i) - 'A' + 1;
        }
        return index - 1;
    }

}
