package lc.mecha.lang;

import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

public class MapUtil {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(MapUtil.class);

    public static void flatten(RowHandler handler, Map map) {
        flatten(handler, map, new ArrayList());
    }

    /**
     * Returns <code>true</code> if the provided map contains at least one key in the provided set of keys.
     */
    public static boolean containsAnyKey(Map a, Set keys) {
        for (Object key : keys) {
            if (a.containsKey(key)) return true;
        }
        return false;
    }

    private static void flatten(RowHandler handler, Map map, ArrayList baseKeys) {
        map.forEach((k, v) -> {
            ArrayList newKeys = (ArrayList) baseKeys.clone();
            newKeys.add(k);

            if (v instanceof Map) {
                flatten(handler, (Map) v, newKeys);
            } else {
                try {
                    handler.row(newKeys, v);
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException();
                }
            }
        });

    }

    public interface RowHandler {
        void row(ArrayList keys, Object value) throws SQLException;
    }
}
