package org.jboss.installer.validators;

import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.core.ValidationResult;
import org.jboss.installer.postinstall.task.LDAPSetupTask;
import org.jboss.installer.test.utils.MockLanguageUtils;
import org.jboss.installer.test.utils.MockLdapServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import static org.junit.Assert.*;

public class LDAPValidatorTest {
    public static final String ldapTestUrl =  "ldap://localhost:10389";
    public static final String ldapAdminDn = "uid=admin,ou=system";
    public static final String ldapAdminPassword = "secret";

    private MockLdapServer ldapServer;
    private LanguageUtils langUtils = new MockLanguageUtils();
    private LDAPValidator dv;

    @Rule
    public TemporaryFolder tempFolder = new TemporaryFolder();

    @Before
    public void setUp() throws Exception {
        ldapServer = new MockLdapServer(tempFolder.getRoot());
        dv = new LDAPValidator(langUtils);
        ldapServer.startServer();
    }

    @After
    public void tearDown() throws Exception {
        ldapServer.stopServer();
        ldapServer = null;
    }

    @Test
    public void testCorrectCredentials() throws Exception {
        LDAPSetupTask.Config config = new LDAPSetupTask.Config("ldap.connection", ldapTestUrl, ldapAdminDn, ldapAdminPassword);

        assertStatusOk(config);
    }

    @Test
    public void testWrongPassword() throws Exception {
        LDAPSetupTask.Config config = new LDAPSetupTask.Config("ldap.connection", ldapTestUrl, ldapAdminDn, "incorrect");

        assertStatusError(config);
    }

    @Test
    public void testWrongDn() throws Exception {
        LDAPSetupTask.Config config = new LDAPSetupTask.Config("ldap.connection", ldapTestUrl, "uid=totallywrong,ou=wrongagain", ldapAdminPassword);

        assertStatusError(config);
    }

    @Test
    public void testWrongUrl() throws Exception {
        LDAPSetupTask.Config config = new LDAPSetupTask.Config("ldap.connection", "ldap://wrongurl:1111", ldapAdminPassword, ldapAdminPassword);

        assertStatusError(config);
    }

    private void assertStatusOk(LDAPSetupTask.Config config){
        ValidationResult result = dv.validateData(config);
        assertEquals(result.getMessage(), ValidationResult.Result.OK, result.getResult());
    }

    public void assertStatusError(LDAPSetupTask.Config config){
        ValidationResult result = dv.validateData(config);
        assertEquals(result.getMessage(), ValidationResult.Result.ERROR, result.getResult());
    }
}