package org.jboss.installer.validators;

import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.core.ValidationResult;
import org.jboss.installer.postinstall.task.LDAPManagementAuthConfig;
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 SearchDnValidatorTest {
    @Rule
    public TemporaryFolder tempFolder = new TemporaryFolder();
    private MockLdapServer ldapServer;
    private LanguageUtils langUtils = new MockLanguageUtils();
    private SearchDnValidator dv = new SearchDnValidator(langUtils);
    private LDAPManagementAuthConfig config = new LDAPManagementAuthConfig("ldap.connection", LDAPValidatorTest.ldapTestUrl,
            LDAPValidatorTest.ldapAdminDn, LDAPValidatorTest.ldapAdminPassword);

    @Before
    public void setUp() throws Exception {

        config.setFilter("uid");
        config.setFilterType(LDAPManagementAuthConfig.FilterType.USERNAME);
        ldapServer = new MockLdapServer(tempFolder.getRoot());
        ldapServer.startServer();
    }

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


    @Test
    public void testExistingDn() throws Exception {
        ldapServer.addUser("cn=Jiggalow Smith,o=TestOrganization","jsmith","Jiggalow Smith", "Smith");
        config.setBaseDN("o=TestOrganization");

        assertStatusOk(config);
    }

    @Test
    public void testNonExistingDn() throws Exception {
        ldapServer.addUser("cn=Jiggalow Smith,o=TestOrganization", "jsmith", "Jiggalow Smith", "Smith");
        config.setBaseDN("o=NonExistentOrganization");
        assertStatusWarning(config);
    }

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

    public void assertStatusWarning(LDAPManagementAuthConfig config){
        ValidationResult result = dv.validateData(config);
        assertEquals(result.getMessage(), ValidationResult.Result.WARNING, result.getResult());
    }
}