package com.distelli.aws;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.BasicSessionCredentials;
import com.distelli.cred.CredPair;
import com.distelli.cred.CredProvider;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

public class TestAWSCredentialsProviderFactory {
    private static Injector INJECTOR = Guice.createInjector();

    @Inject
    private AWSCredentialsProviderFactory _awsCredentialsProviderFactory;

    @Before
    public void beforeTest() {
        INJECTOR.injectMembers(this);
    }

    @Test
    public void testBasic() {
        CredPair credPair1 = new CredPair()
            .withKeyId("one")
            .withSecret("secret1");
        AtomicInteger refreshCount1 = new AtomicInteger();
        CredProvider credProvider1 = new CredProvider() {
                public CredPair getCredPair() {
                    return credPair1;
                }
                public void refresh() {
                    refreshCount1.incrementAndGet();
                }
            };
                    
        AWSCredentialsProvider credProvider = _awsCredentialsProviderFactory.create(credProvider1);
        AWSCredentials creds = credProvider.getCredentials();
        assertThat(creds, instanceOf(BasicAWSCredentials.class));
        assertEquals("one", creds.getAWSAccessKeyId());
        assertEquals("secret1", creds.getAWSSecretKey());
        assertEquals(0, refreshCount1.get());
        credProvider.refresh();
        assertEquals(1, refreshCount1.get());
    }

    @Test
    public void testSession() {
        CredPair credPair2 = new CredPair()
            .withKeyId("two")
            .withSecret("secret2\u001ESESSION");
        CredProvider credProvider2 = () -> credPair2;
        AWSCredentialsProvider credProvider = _awsCredentialsProviderFactory.create(credProvider2);
        AWSCredentials creds = credProvider.getCredentials();
        assertThat(creds, instanceOf(BasicSessionCredentials.class));
        assertEquals("two", creds.getAWSAccessKeyId());
        assertEquals("secret2", creds.getAWSSecretKey());
        assertEquals("SESSION", ((BasicSessionCredentials)creds).getSessionToken());
    }
}