package jp.sourceforge.glad.collection.iteration;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import jp.sourceforge.glad.collection.closure.ClosureSupport;
import jp.sourceforge.glad.collection.function.Function;
import junit.framework.TestCase;

public class MapIterationHandlerTest extends TestCase {

    MapIterationHandler<String, Long> handler;

    protected void setUp() throws Exception {
        Map<String, Long> source = new TreeMap<String, Long>();
        source.put("a", 1L);
        source.put("c", 2L);
        source.put("b", 3L);
        handler = new MapIterationHandler<String, Long>(source);
    }

    protected void tearDown() throws Exception {
        handler = null;
    }

    public void testIterate() {
        final Map<String, Long> target = new LinkedHashMap<String, Long>();
        handler.iterate(new ClosureSupport<Entry<String, Long>>() {
            public void execute(Entry<String, Long> each) {
                target.put(each.getKey(), each.getValue());
            }
        });
        assertEquals(3, target.size());
        assertEquals("{a=1, b=3, c=2}", target.toString());
    }

    public void testConvert() {
        IterationHandler<String> adapter =
                new IterationHandlerAdapter<Entry<String, Long>, String>(
                        handler,
        new Function<Entry<String, Long>, String>() {
            public String apply(Entry<String, Long> source) {
                return source.getKey() + ":" + source.getValue();
            }
        });
        final List<String> target = new ArrayList<String>();
        adapter.iterate(new ClosureSupport<String>() {
            public void execute(String each) {
                target.add(each);
            }
        });
        assertEquals(3, target.size());
        assertEquals("[a:1, b:3, c:2]", target.toString());
    }

}
