package com.nibado.projects.advent;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.nibado.projects.advent.Util.printAnswer;
import static com.nibado.projects.advent.Util.readResourceAsJson;

public class Day12 implements Runnable {

    @Override
    public void run() {
        JsonNode input = readResourceAsJson("/day12.txt");

        printAnswer(12, "One", sumTree(input, n -> false));
        printAnswer(12, "Two", sumTree(input, n -> hasValue(n, "red")));
    }

    public int sumTree(JsonNode node, Function<JsonNode, Boolean> filter) {
        if(node.isInt()) {
            return node.asInt();
        }
        if(filter.apply(node)) {
            return 0;
        }
        final AtomicInteger sum = new AtomicInteger(0);

        node.forEach(n -> sum.addAndGet(sumTree(n, filter)));

        return sum.get();
    }

    public boolean hasValue(JsonNode node, String value) {
        Iterator<JsonNode> iter = node.iterator();

        if(!node.isObject()) {
            return false;
        }
        while(iter.hasNext()) {
            if(value.equals(iter.next().asText())) {
                return true;
            }
        }

        return false;
    }

    public static void main(String[] argv) {
        new Day12().run();
    }
}

@@ -81,114 +81,8 @@
 ode;
-%0Aimport com.fasterxml.jackson.databind.ObjectMapper;%0Aimport com.fasterxml.jackson.databind.node.ArrayNode;
 %0A%0Aim
@@ -110,30 +110,8 @@
 or;%0A
-import java.util.Map;%0A
 impo
@@ -152,24 +152,24 @@
 micInteger;%0A
+
 import java.
@@ -195,76 +195,8 @@
 ion;
-%0Aimport java.util.stream.Collectors;%0Aimport java.util.stream.Stream;
 %0A%0Aim

Clean up imports