/*
 * Copyright 2017 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.keycloak.testsuite.federation.ldap;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.Response;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.TargetsContainer;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.component.ComponentModel;
import org.keycloak.component.ComponentValidationException;
import org.keycloak.models.LDAPConstants;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.UserModelDelegate;
import org.keycloak.representations.idm.ComponentRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.storage.ldap.LDAPStorageProvider;
import org.keycloak.storage.ldap.LDAPUtils;
import org.keycloak.storage.ldap.idm.model.LDAPObject;
import org.keycloak.storage.ldap.mappers.LDAPStorageMapper;
import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper;
import org.keycloak.testsuite.client.KeycloakTestingClient;
import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
import org.keycloak.testsuite.util.LDAPRule;
import org.keycloak.testsuite.util.LDAPTestUtils;

import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT;

/**
 * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LDAPBinaryAttributesTest extends AbstractLDAPTest {

    @ClassRule
    public static LDAPRule ldapRule = new LDAPRule();

    @Deployment
    @TargetsContainer(AUTH_SERVER_CURRENT)
    public static WebArchive deploy() {
        return RunOnServerDeployment.create(UserResource.class, AbstractLDAPTest.class)
                .addPackages(true,
                        "org.keycloak.testsuite",
                        "org.keycloak.testsuite.federation.ldap");
    }


    @Override
    protected LDAPRule getLDAPRule() {
        return ldapRule;
    }

    @Override
    protected void afterImportTestRealm() {
        testingClient.server().run(session -> {
            LDAPTestContext ctx = LDAPTestContext.init(session);
            RealmModel appRealm = ctx.getRealm();

            LDAPTestUtils.addZipCodeLDAPMapper(appRealm, ctx.getLdapModel());

            // Delete all LDAP users and add some new for testing
            LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
            LDAPTestUtils.removeAllLDAPUsers(ldapFedProvider, appRealm);

//            LDAPObject john = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "johnkeycloak", "John", "Doe", "john@email.org", null, "1234");
//            LDAPTestUtils.updateLDAPPassword(ldapFedProvider, john, "Password1");
//
//            LDAPObject existing = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "existing", "Existing", "Foo", "existing@email.org", null, "5678");

            appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true);

        });
    }



    private static final String JPEG_PHOTO_BASE64 = " ";



    @After
    public void after() {
        ComponentRepresentation jpegMapper = adminClient.realm("test").components().query(ldapModelId, LDAPStorageMapper.class.getName(), "jpeg-mapper").get(0);
        adminClient.realm("test").components().component(jpegMapper.getId()).remove();
    }


    // Test invalid mapper configuration - validation exception thrown
    @Test
    public void test01InvalidMapperConfiguration() {
        testingClient.server().run(session -> {
            LDAPTestContext ctx = LDAPTestContext.init(session);
            RealmModel appRealm = ctx.getRealm();

            ComponentModel ldapComponentMapper = LDAPTestUtils.addUserAttributeMapper(appRealm, ctx.getLdapModel(), "jpeg-mapper", LDAPConstants.JPEG_PHOTO, LDAPConstants.JPEG_PHOTO);

            ldapComponentMapper.put(UserAttributeLDAPStorageMapper.IS_BINARY_ATTRIBUTE, true);
            try {
                appRealm.updateComponent(ldapComponentMapper);
                Assert.fail("Not expected to successfully update mapper");
            } catch (ComponentValidationException cve) {
                // Expected
            }

        });
    }


    @Test
    public void test02ReadOnly() {
        String mapperId = addPhotoMapper(testingClient);

        testingClient.server().run(session -> {
            LDAPTestContext ctx = LDAPTestContext.init(session);
            RealmModel appRealm = ctx.getRealm();

            // Add user directly to LDAP
            LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
            addLDAPUser(ldapFedProvider, appRealm, "johnphoto", "John", "Photo", "john@photo.org", JPEG_PHOTO_BASE64);

            // Set mapper to be read-only
            ComponentModel ldapComponentMapper = appRealm.getComponent(mapperId);
            ldapComponentMapper.put(UserAttributeLDAPStorageMapper.READ_ONLY, true);
            appRealm.updateComponent(ldapComponentMapper);
        });

        // Assert john found
        getUserAndAssertPhoto("johnphoto", true);
    }


    @Test
    public void test03WritableMapper() {
        String mapperId = addPhotoMapper(testingClient);

        // Create user joe with jpegPHoto
        UserRepresentation joe = new UserRepresentation();
        joe.setUsername("joephoto");
        joe.setEmail("joe@photo.org");
        joe.setAttributes(Collections.singletonMap(LDAPConstants.JPEG_PHOTO, Arrays.asList(JPEG_PHOTO_BASE64)));
        Response response = adminClient.realm("test").users().create(joe);
        response.close();


        // Assert he is found including jpegPhoto
        joe = getUserAndAssertPhoto("joephoto", true);


        // Try to update him with some big non-LDAP mapped attribute. It will fail
        try {
            joe.getAttributes().put("someOtherPhoto", Arrays.asList(JPEG_PHOTO_BASE64));
            adminClient.realm("test").users().get(joe.getId()).update(joe);
            Assert.fail("Not expected to successfully update user");
        } catch (ClientErrorException cee) {
            // Expected
        }

        // Remove jpegPhoto attribute and assert it was successfully removed
        joe.getAttributes().remove("someOtherPhoto");
        joe.getAttributes().remove(LDAPConstants.JPEG_PHOTO);
        adminClient.realm("test").users().get(joe.getId()).update(joe);
        getUserAndAssertPhoto("joephoto", false);
    }


    private static String addPhotoMapper(KeycloakTestingClient testingClient) {
        return testingClient.server().fetch(session -> {
            LDAPTestContext ctx = LDAPTestContext.init(session);
            RealmModel appRealm = ctx.getRealm();

            ComponentModel ldapComponentMapper = LDAPTestUtils.addUserAttributeMapper(appRealm, ctx.getLdapModel(), "jpeg-mapper", LDAPConstants.JPEG_PHOTO, LDAPConstants.JPEG_PHOTO);

            ldapComponentMapper.put(UserAttributeLDAPStorageMapper.IS_BINARY_ATTRIBUTE, true);
            ldapComponentMapper.put(UserAttributeLDAPStorageMapper.ALWAYS_READ_VALUE_FROM_LDAP, true);
            appRealm.updateComponent(ldapComponentMapper);
            return ldapComponentMapper.getId();
        }, String.class);
    }


    private static LDAPObject addLDAPUser(LDAPStorageProvider ldapProvider, RealmModel realm, final String username,
                                         final String firstName, final String lastName, final String email, String jpegPhoto) {
        UserModel helperUser = new UserModelDelegate(null) {

            @Override
            public String getUsername() {
                return username;
            }

            @Override
            public String getFirstName() {
                return firstName;
            }

            @Override
            public String getLastName() {
                return lastName;
            }

            @Override
            public String getEmail() {
                return email;
            }

            @Override
            public List<String> getAttribute(String name) {
                if (LDAPConstants.JPEG_PHOTO.equals(name)) {
                    return Arrays.asList(jpegPhoto);
                } else {
                    return Collections.emptyList();
                }
            }
        };
        return LDAPUtils.addUserToLDAP(ldapProvider, realm, helperUser);
    }


    private UserRepresentation getUserAndAssertPhoto(String username, boolean isPhotoExpected) {
        List<UserRepresentation> johns = adminClient.realm("test").users().search(username, 0, 10);
        Assert.assertEquals(1, johns.size());
        UserRepresentation john = johns.get(0);
        Assert.assertEquals(username, john.getUsername());
        Assert.assertTrue(john.getAttributes().containsKey(LDAPConstants.LDAP_ID)); // Doublecheck it's the LDAP mapped user

        if (isPhotoExpected) {
            Assert.assertEquals(JPEG_PHOTO_BASE64, john.getAttributes().get(LDAPConstants.JPEG_PHOTO).get(0));
        } else {
            Assert.assertFalse(john.getAttributes().containsKey(LDAPConstants.JPEG_PHOTO));
        }
        return john;
    }

}
