package net.ranides.assira.reflection.util;

import net.ranides.assira.generic.Ref;
import org.junit.Test;

import net.ranides.assira.collection.query.CQuery;
import net.ranides.assira.io.uri.URIHandler;

import java.nio.charset.Charset;
import java.nio.charset.spi.CharsetProvider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import static org.junit.Assert.*;

public class ServiceScannerTest {

    @Test
    public void simple() {
        ServiceScanner<URIHandler> handlers = ServiceScanner.scanner(URIHandler.class);

        assertTrue( handlers.names().size() > 0 );
        assertNotNull(handlers.services().first().orElse(null) );
    }

    @Test
    public void merge() {
        ServiceScanner<CharsetProvider> charsets = ServiceScanner.scanner(CharsetProvider.class);

        assertTrue( charsets.names().size() > 1 );
        assertNotNull(charsets.services().first().orElse(null) );

        assertNotNull(charsets.services().filter(v -> v instanceof SpecialCharset).first().orElse(null) );
    }

    @Test
    public void lazy() {
        List<String> names = new ArrayList<>();

        CQuery<URIHandler> query = ServiceScanner.scanner(URIHandler.class)
            .resolver(name -> {
                names.add(name);
                return Ref.empty();
            })
            .services()
            .limit(2);

        List<?> list = query.list();

        assertEquals(2,list.size());
        assertEquals(2, names.size());
    }

    public static class SpecialCharset extends CharsetProvider {

        public SpecialCharset() {
            // do nothing
        }

        @Override
        public Iterator<Charset> charsets() {
            return Collections.emptyIterator();
        }

        @Override
        public Charset charsetForName(String charsetName) {
            return null;
        }
    }
}