/*
 * 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 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.UserProfileResource;
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.representations.userprofile.config.UPAttribute;
import org.keycloak.representations.userprofile.config.UPAttributePermissions;
import org.keycloak.representations.userprofile.config.UPConfig;
import org.keycloak.storage.UserStoragePrivateUtil;
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.forms.VerifyProfileTest;
import org.keycloak.testsuite.util.LDAPRule;
import org.keycloak.testsuite.util.LDAPTestUtils;

import jakarta.ws.rs.core.Response;
import org.keycloak.validate.validators.LengthValidator;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * @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();

    @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);

        });

        // User profile unmanaged attributes supported
        UserProfileResource userProfileRes = testRealm().users().userProfile();
        VerifyProfileTest.enableUnmanagedAttributes(userProfileRes);
    }


    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);

        // Allow long attribute for photos
        UPConfig upc = adminClient.realm("test").users().userProfile().getConfiguration();
        UPAttribute upa = new UPAttribute("jpegPhoto");
        upa.setValidations(Map.of(LengthValidator.ID, Map.of(LengthValidator.KEY_MIN, "0", LengthValidator.KEY_MAX, JPEG_PHOTO_BASE64.length() * 2)));
        upa.setPermissions(new UPAttributePermissions(Set.of("user", "admin"), Set.of("user", "admin")));
        upc.getAttributes().add(upa);
        adminClient.realm("test").users().userProfile().update(upc);

        // Create user joe with jpegPhoto
        UserRepresentation joe = new UserRepresentation();
        joe.setUsername("joephoto");
        joe.setEmail("joe@photo.org");
        joe.setAttributes(Collections.singletonMap(LDAPConstants.JPEG_PHOTO, List.of(JPEG_PHOTO_BASE64)));

        try (Response response = adminClient.realm("test").users().create(joe)) {
            assertThat(response.getStatusInfo().getStatusCode(), equalTo(201));
        }

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

        // Assert that local storage doesn't contain LDAPConstants.JPEG_PHOTO, it should be stored in the LDAP
        String joeId = joe.getId();
        testingClient.server().run(session -> {
            RealmModel test = session.realms().getRealmByName("test");
            UserModel userById = UserStoragePrivateUtil.userLocalStorage(session).getUserById(test, joeId);

            assertThat(userById.getAttributes().get(LDAPConstants.JPEG_PHOTO), is(nullValue()));
        });


        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 getEmail() {
                return email;
            }

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

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

            @Override
            public String getFirstAttribute(String name) {
                if (UserModel.LAST_NAME.equals(name)) {
                    return lastName;
                } else if (UserModel.FIRST_NAME.equals(name)) {
                    return firstName;
                } else if (UserModel.EMAIL.equals(name)) {
                    return email;
                } else if (UserModel.USERNAME.equals(name)) {
                    return username;
                }
                return super.getFirstAttribute(name);
            }

            @Override
            public Stream<String> getAttributeStream(String name) {
                if (UserModel.LAST_NAME.equals(name)) {
                    return Stream.of(lastName);
                } else if (UserModel.FIRST_NAME.equals(name)) {
                    return Stream.of(firstName);
                } else if (UserModel.EMAIL.equals(name)) {
                    return Stream.of(email);
                } else if (UserModel.USERNAME.equals(name)) {
                    return Stream.of(username);
                } else if (LDAPConstants.JPEG_PHOTO.equals(name)) {
                    return Stream.of(jpegPhoto);
                } else {
                    return Stream.empty();
                }
            }
        };
        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;
    }

}
