package org.mercury_im.messenger.learning_tests.dagger;

import org.junit.Test;

import javax.inject.Inject;
import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

import static junit.framework.TestCase.assertEquals;

public class DaggerTest {

    @dagger.Component(modules = {SingletonModule.class})
    @Singleton
    public interface Component {

        void inject(Consumer consumer);
    }

    @Module
    public class NewInstanceModule {

        private int DEPENDENCY_INDEX = 0;
        private final String MODULE_NAME;

        public NewInstanceModule(String moduleName) {
            this.MODULE_NAME = moduleName;
        }

        @Provides
        Dependency provideDependency() {
            return new Dependency(DEPENDENCY_INDEX++, MODULE_NAME);
        }
    }

    @Module
    public class SingletonModule {
        private int DEPENDENCY_INDEX = 0;
        private final String MODULE_NAME;

        public SingletonModule(String moduleName) {
            this.MODULE_NAME = moduleName;
        }

        @Provides
        @Singleton
        Dependency provideDependency() {
            return new Dependency(DEPENDENCY_INDEX++, MODULE_NAME);
        }
    }


    public static class Dependency {

        final int index;
        final String moduleName;

        @Inject
        public Dependency(int index, String moduleName) {
            this.index = index;
            this.moduleName = moduleName;
        }

        public int getIndex() {
            return index;
        }

        public String getModuleName() {
            return moduleName;
        }
    }

    public static class Consumer {

        @Inject
        Dependency dependency;

        public Consumer() {

        }

        public Dependency getDependency() {
            return dependency;
        }
    }

    @Test
    public void test() {
        Component component0 = DaggerDaggerTest_Component.builder().singletonModule(new SingletonModule("First")).build();

        Consumer consumer0 = new Consumer();
        Consumer consumer1 = new Consumer();

        component0.inject(consumer0);
        component0.inject(consumer1);

        Component component1 = DaggerDaggerTest_Component.builder().singletonModule(new SingletonModule("Second")).build();

        Consumer consumer2 = new Consumer();
        Consumer consumer3 = new Consumer();
        component1.inject(consumer2);
        component1.inject(consumer3);

        assertEquals(0, consumer0.getDependency().getIndex());
        assertEquals(1, consumer1.getDependency().getIndex());
        assertEquals(0, consumer2.getDependency().getIndex());
        assertEquals(1, consumer3.getDependency().getIndex());
    }
}
