package com.lingniu.ingest.core.dispatcher;

import com.lingniu.ingest.api.ProtocolId;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Method;

import static org.assertj.core.api.Assertions.assertThat;

class HandlerRegistryTest {

    @Test
    void exactCommandMatchTakesPrecedenceOverWildcardHandlers() throws Exception {
        HandlerRegistry registry = new HandlerRegistry();
        Object bean = new SampleHandlers();
        Method exact = SampleHandlers.class.getMethod("exact", Object.class);
        Method wildcard = SampleHandlers.class.getMethod("wildcard", Object.class);
        HandlerDefinition exactDef = definition(0x0200, "exact", bean, exact);
        HandlerDefinition wildcardDef = definition(0, "wildcard", bean, wildcard);

        registry.register(exactDef);
        registry.register(wildcardDef);

        assertThat(registry.resolve(ProtocolId.XINDA_PUSH, 0x0200, 0))
                .containsExactly(exactDef);
        assertThat(registry.resolve(ProtocolId.XINDA_PUSH, 0x0500, 0))
                .containsExactly(wildcardDef);
    }

    private static HandlerDefinition definition(int command, String desc, Object bean, Method method) {
        return new HandlerDefinition(
                ProtocolId.XINDA_PUSH,
                command,
                0,
                desc,
                bean,
                method,
                Object.class,
                null,
                null,
                null);
    }

    public static final class SampleHandlers {
        public void exact(Object ignored) {
        }

        public void wildcard(Object ignored) {
        }
    }
}
