/*
 * Copyright 2016 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.models.jpa;

import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.jpa.entities.ClientAttributeEntity;
import org.keycloak.models.jpa.entities.ClientEntity;
import org.keycloak.models.jpa.entities.ClientScopeClientMappingEntity;
import org.keycloak.models.jpa.entities.ProtocolMapperEntity;
import org.keycloak.models.jpa.entities.RoleEntity;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import br.ufrgs.inf.prosoft.cache.*;

/**
 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
 * @version $Revision: 1 $
 */
public class ClientAdapter implements ClientModel, JpaModel<ClientEntity> {

    protected KeycloakSession session;
    protected RealmModel realm;
    protected EntityManager em;
    protected ClientEntity entity;

    public ClientAdapter(RealmModel realm, EntityManager em, KeycloakSession session, ClientEntity entity) {
        this.session = session;
        this.realm = realm;
        this.em = em;
        this.entity = entity;
    }

// public static CaffeineGetterCache<ClientEntity> getEntity = new CaffeineGetterCache<>("static-getter:ClientAdapter.getEntity", 120000);

    public ClientEntity getEntity() {
// return getEntity.computeIfAbsent(() -> {
        return entity;
// }, 120000);
    }

    @Override
    public String getId() {
        return getEntity().getId();
    }

    @Override
    public RealmModel getRealm() {
        return realm;
    }

    @Override
    public String getName() {
        return getEntity().getName();
    }

    @Override
    public void setName(String name) {
        // getEntity.invalidate();
        entity.setName(name);
    }

    @Override
    public String getDescription() { return getEntity().getDescription(); }

    @Override
    public void setDescription(String description) { 
// getEntity.invalidate();
        entity.setDescription(description); }

    @Override
    public boolean isEnabled() {
        return getEntity().isEnabled();
    }

    @Override
    public void setEnabled(boolean enabled) {
        // getEntity.invalidate();
        entity.setEnabled(enabled);
    }

    @Override
    public boolean isPublicClient() {
        return getEntity().isPublicClient();
    }

    @Override
    public void setPublicClient(boolean flag) {
        // getEntity.invalidate();
        entity.setPublicClient(flag);
    }

    @Override
    public boolean isFrontchannelLogout() {
        return getEntity().isFrontchannelLogout();
    }

    @Override
    public void setFrontchannelLogout(boolean flag) {
        // getEntity.invalidate();
        entity.setFrontchannelLogout(flag);
    }

    @Override
    public boolean isFullScopeAllowed() {
        return getEntity().isFullScopeAllowed();
    }

    @Override
    public void setFullScopeAllowed(boolean value) {
        // getEntity.invalidate();
        entity.setFullScopeAllowed(value);
    }

    @Override
    public Set<String> getWebOrigins() {
        Set<String> result = new HashSet<String>();
        result.addAll(entity.getWebOrigins());
        return result;
    }



    @Override
    public void setWebOrigins(Set<String> webOrigins) {
        // getEntity.invalidate();
        entity.setWebOrigins(webOrigins);
    }

    @Override
    public void addWebOrigin(String webOrigin) {
        entity.getWebOrigins().add(webOrigin);
    }

    @Override
    public void removeWebOrigin(String webOrigin) {
        entity.getWebOrigins().remove(webOrigin);
    }

    @Override
    public Set<String> getRedirectUris() {
        Set<String> result = new HashSet<String>();
        result.addAll(getEntity().getRedirectUris());
        return result;
    }

    @Override
    public void setRedirectUris(Set<String> redirectUris) {
        // getEntity.invalidate();
        entity.setRedirectUris(redirectUris);
    }

    @Override
    public void addRedirectUri(String redirectUri) {
        getEntity().getRedirectUris().add(redirectUri);
    }

    @Override
    public void removeRedirectUri(String redirectUri) {
        getEntity().getRedirectUris().remove(redirectUri);
    }

    @Override
    public String getClientAuthenticatorType() {
        return getEntity().getClientAuthenticatorType();
    }

    @Override
    public void setClientAuthenticatorType(String clientAuthenticatorType) {
        // getEntity.invalidate();
        entity.setClientAuthenticatorType(clientAuthenticatorType);
    }

    @Override
    public String getSecret() {
        return getEntity().getSecret();
    }

    @Override
    public void setSecret(String secret) {
        // getEntity.invalidate();
        entity.setSecret(secret);
    }

    @Override
    public String getRegistrationToken() {
        return getEntity().getRegistrationToken();
    }

    @Override
    public void setRegistrationToken(String registrationToken) {
        // getEntity.invalidate();
        entity.setRegistrationToken(registrationToken);
    }

    @Override
    public boolean validateSecret(String secret) {
        return MessageDigest.isEqual(secret.getBytes(), getEntity().getSecret().getBytes());
    }

    @Override
    public int getNotBefore() {
        return getEntity().getNotBefore();
    }

    @Override
    public void setNotBefore(int notBefore) {
        // getEntity.invalidate();
        entity.setNotBefore(notBefore);
    }

    @Override
    public Set<RoleModel> getRealmScopeMappings() {
        Set<RoleModel> roleMappings = getScopeMappings();

        Set<RoleModel> appRoles = new HashSet<>();
        for (RoleModel role : roleMappings) {
            RoleContainerModel container = role.getContainer();
            if (container instanceof RealmModel) {
                if (((RealmModel) container).getId().equals(realm.getId())) {
                    appRoles.add(role);
                }
            }
        }

        return appRoles;
    }

    @Override
    public Set<RoleModel> getScopeMappings() {
        return entity.getScopeMapping().stream()
                .map(RoleEntity::getId)
                .map(realm::getRoleById)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
    }

    @Override
    public void addScopeMapping(RoleModel role) {
        RoleEntity roleEntity = RoleAdapter.toRoleEntity(role, em);
        entity.getScopeMapping().add(roleEntity);
    }

    @Override
    public void deleteScopeMapping(RoleModel role) {
        entity.getScopeMapping().remove(RoleAdapter.toRoleEntity(role, em));
    }

    @Override
    public String getProtocol() {
        return getEntity().getProtocol();
    }

    @Override
    public void setProtocol(String protocol) {
        // getEntity.invalidate();
        entity.setProtocol(protocol);

    }

    @Override
    public void setAuthenticationFlowBindingOverride(String name, String value) {
        // getEntity.invalidate();
        entity.getAuthFlowBindings().put(name, value);

    }

    @Override
    public void removeAuthenticationFlowBindingOverride(String name) {
        // getEntity.invalidate();
        entity.getAuthFlowBindings().remove(name);
    }

    @Override
    public String getAuthenticationFlowBindingOverride(String name) {
        // getEntity.invalidate();
        return entity.getAuthFlowBindings().get(name);
    }

    @Override
    public Map<String, String> getAuthenticationFlowBindingOverrides() {
        Map<String, String> copy = new HashMap<>();
        copy.putAll(entity.getAuthFlowBindings());
        return copy;
    }

    @Override
    public void setAttribute(String name, String value) {
        // getEntity.invalidate();
        for (ClientAttributeEntity attr : entity.getAttributes()) {
            if (attr.getName().equals(name)) {
                attr.setValue(value);
                return;
            }
        }

        ClientAttributeEntity attr = new ClientAttributeEntity();
        attr.setName(name);
        attr.setValue(value);
        attr.setClient(entity);
        em.persist(attr);
        entity.getAttributes().add(attr);
    }

    @Override
    public void removeAttribute(String name) {
        // getEntity.invalidate();
        Iterator<ClientAttributeEntity> it = entity.getAttributes().iterator();
        while (it.hasNext()) {
            ClientAttributeEntity attr = it.next();
            if (attr.getName().equals(name)) {
                it.remove();
                em.remove(attr);
            }
        }
    }

    @Override
    public String getAttribute(String name) {
        return getAttributes().get(name);
    }

    @Override
    public Map<String, String> getAttributes() {
        Map<String, String> attrs = new HashMap<>();
        for (ClientAttributeEntity attr : entity.getAttributes()) {
            attrs.put(attr.getName(), attr.getValue());
        }
        return attrs;
    }

    @Override
    public void addClientScope(ClientScopeModel clientScope, boolean defaultScope) {
        // getEntity.invalidate();
        if (getClientScopes(defaultScope, false).containsKey(clientScope.getName())) return;

        ClientScopeClientMappingEntity entity = new ClientScopeClientMappingEntity();
        entity.setClientScope(ClientScopeAdapter.toClientScopeEntity(clientScope, em));
        entity.setClient(getEntity());
        entity.setDefaultScope(defaultScope);
        em.persist(entity);
        em.flush();
        em.detach(entity);
    }

    @Override
    public void removeClientScope(ClientScopeModel clientScope) {
        int numRemoved = em.createNamedQuery("deleteClientScopeClientMapping")
                .setParameter("clientScope", ClientScopeAdapter.toClientScopeEntity(clientScope, em))
                .setParameter("client", getEntity())
                .executeUpdate();
        em.flush();
    }

    @Override
    public Map<String, ClientScopeModel> getClientScopes(boolean defaultScope, boolean filterByProtocol) {
        TypedQuery<String> query = em.createNamedQuery("clientScopeClientMappingIdsByClient", String.class);
        query.setParameter("client", getEntity());
        query.setParameter("defaultScope", defaultScope);
        List<String> ids = query.getResultList();

        // Defaults to openid-connect
        String clientProtocol = getProtocol() == null ? OIDCLoginProtocol.LOGIN_PROTOCOL : getProtocol();

        Map<String, ClientScopeModel> clientScopes = new HashMap<>();
        for (String clientScopeId : ids) {
            ClientScopeModel clientScope = realm.getClientScopeById(clientScopeId);
            if (clientScope == null) continue;
            if (!filterByProtocol || clientScope.getProtocol().equals(clientProtocol)) {
                clientScopes.put(clientScope.getName(), clientScope);
            }
        }
        return clientScopes;
    }


    public static boolean contains(String str, String[] array) {
        for (String s : array) {
            if (str.equals(s)) return true;
        }
        return false;
    }

    @Override
    public Set<ProtocolMapperModel> getProtocolMappers() {
        // getEntity.invalidate();
        Set<ProtocolMapperModel> mappings = new HashSet<ProtocolMapperModel>();
        for (ProtocolMapperEntity entity : getEntity().getProtocolMappers()) {
            ProtocolMapperModel mapping = new ProtocolMapperModel();
            mapping.setId(entity.getId());
            mapping.setName(entity.getName());
            mapping.setProtocol(entity.getProtocol());
            mapping.setProtocolMapper(entity.getProtocolMapper());
            Map<String, String> config = new HashMap<String, String>();
            if (entity.getConfig() != null) {
                config.putAll(entity.getConfig());
            }
            mapping.setConfig(config);
            mappings.add(mapping);
        }
        return mappings;
    }

    @Override
    public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
        // getEntity.invalidate();
        if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) {
            throw new ModelDuplicateException("Protocol mapper name must be unique per protocol");
        }
        String id = model.getId() != null ? model.getId() : KeycloakModelUtils.generateId();
        ProtocolMapperEntity entity = new ProtocolMapperEntity();
        entity.setId(id);
        entity.setName(model.getName());
        entity.setProtocol(model.getProtocol());
        entity.setProtocolMapper(model.getProtocolMapper());
        entity.setClient(this.entity);
        entity.setConfig(model.getConfig());

        em.persist(entity);
        this.entity.getProtocolMappers().add(entity);
        return entityToModel(entity);
    }

    protected ProtocolMapperEntity getProtocolMapperEntity(String id) {
        // getEntity.invalidate();
        for (ProtocolMapperEntity entity : entity.getProtocolMappers()) {
            if (entity.getId().equals(id)) {
                return entity;
            }
        }
        return null;

    }

    protected ProtocolMapperEntity getProtocolMapperEntityByName(String protocol, String name) {
        // getEntity.invalidate();
        for (ProtocolMapperEntity entity : entity.getProtocolMappers()) {
            if (entity.getProtocol().equals(protocol) && entity.getName().equals(name)) {
                return entity;
            }
        }
        return null;

    }

    @Override
    public void removeProtocolMapper(ProtocolMapperModel mapping) {
        // getEntity.invalidate();
        ProtocolMapperEntity toDelete = getProtocolMapperEntity(mapping.getId());
        if (toDelete != null) {
            session.users().preRemove(mapping);

            this.entity.getProtocolMappers().remove(toDelete);
            em.remove(toDelete);
        }

    }

    @Override
    public void updateProtocolMapper(ProtocolMapperModel mapping) {
        // getEntity.invalidate();
        ProtocolMapperEntity entity = getProtocolMapperEntity(mapping.getId());
        entity.setProtocolMapper(mapping.getProtocolMapper());
        if (entity.getConfig() == null) {
            entity.setConfig(mapping.getConfig());
        } else {
            entity.getConfig().clear();
            entity.getConfig().putAll(mapping.getConfig());
        }
        em.flush();

    }

    @Override
    public ProtocolMapperModel getProtocolMapperById(String id) {
        ProtocolMapperEntity entity = getProtocolMapperEntity(id);
        if (entity == null) return null;
        return entityToModel(entity);
    }

    @Override
    public ProtocolMapperModel getProtocolMapperByName(String protocol, String name) {
        ProtocolMapperEntity entity = getProtocolMapperEntityByName(protocol, name);
        if (entity == null) return null;
        return entityToModel(entity);
    }

    protected ProtocolMapperModel entityToModel(ProtocolMapperEntity entity) {
        ProtocolMapperModel mapping = new ProtocolMapperModel();
        mapping.setId(entity.getId());
        mapping.setName(entity.getName());
        mapping.setProtocol(entity.getProtocol());
        mapping.setProtocolMapper(entity.getProtocolMapper());
        Map<String, String> config = new HashMap<String, String>();
        if (entity.getConfig() != null) config.putAll(entity.getConfig());
        mapping.setConfig(config);
        return mapping;
    }

    @Override
    public void updateClient() {
        em.flush();
        session.getKeycloakSessionFactory().publish(new RealmModel.ClientUpdatedEvent() {

            @Override
            public ClientModel getUpdatedClient() {
                return ClientAdapter.this;
            }

            @Override
            public KeycloakSession getKeycloakSession() {
                return session;
            }
        });
    }

    @Override
    public String getClientId() {
        return getEntity().getClientId();
    }

    @Override
    public void setClientId(String clientId) {
        // getEntity.invalidate();
        entity.setClientId(clientId);
    }

    @Override
    public boolean isSurrogateAuthRequired() {
        return getEntity().isSurrogateAuthRequired();
    }

    @Override
    public void setSurrogateAuthRequired(boolean surrogateAuthRequired) {
        // getEntity.invalidate();
        entity.setSurrogateAuthRequired(surrogateAuthRequired);
    }

    @Override
    public String getManagementUrl() {
        return getEntity().getManagementUrl();
    }

    @Override
    public void setManagementUrl(String url) {
        // getEntity.invalidate();
        entity.setManagementUrl(url);
    }

    @Override
    public String getRootUrl() {
        return getEntity().getRootUrl();
    }

    @Override
    public void setRootUrl(String url) {
        // getEntity.invalidate();
        entity.setRootUrl(url);
    }

    @Override
    public String getBaseUrl() {
        return getEntity().getBaseUrl();
    }

    @Override
    public void setBaseUrl(String url) {
        // getEntity.invalidate();
        entity.setBaseUrl(url);
    }

    @Override
    public boolean isBearerOnly() {
        return getEntity().isBearerOnly();
    }

    @Override
    public void setBearerOnly(boolean only) {
        // getEntity.invalidate();
        entity.setBearerOnly(only);
    }

    @Override
    public boolean isConsentRequired() {
        return getEntity().isConsentRequired();
    }

    @Override
    public void setConsentRequired(boolean consentRequired) {
        // getEntity.invalidate();
        entity.setConsentRequired(consentRequired);
    }

    @Override
    public boolean isStandardFlowEnabled() {
        return getEntity().isStandardFlowEnabled();
    }

    @Override
    public void setStandardFlowEnabled(boolean standardFlowEnabled) {
        // getEntity.invalidate();
        entity.setStandardFlowEnabled(standardFlowEnabled);
    }

    @Override
    public boolean isImplicitFlowEnabled() {
        return getEntity().isImplicitFlowEnabled();
    }

    @Override
    public void setImplicitFlowEnabled(boolean implicitFlowEnabled) {
        // getEntity.invalidate();
        entity.setImplicitFlowEnabled(implicitFlowEnabled);
    }

    @Override
    public boolean isDirectAccessGrantsEnabled() {
        return getEntity().isDirectAccessGrantsEnabled();
    }

    @Override
    public void setDirectAccessGrantsEnabled(boolean directAccessGrantsEnabled) {
        // getEntity.invalidate();
        entity.setDirectAccessGrantsEnabled(directAccessGrantsEnabled);
    }

    @Override
    public boolean isServiceAccountsEnabled() {
        return getEntity().isServiceAccountsEnabled();
    }

    @Override
    public void setServiceAccountsEnabled(boolean serviceAccountsEnabled) {
        // getEntity.invalidate();
        entity.setServiceAccountsEnabled(serviceAccountsEnabled);
    }

    @Override
    public RoleModel getRole(String name) {
        return session.realms().getClientRole(realm, this, name);
    }

    @Override
    public RoleModel addRole(String name) {
        return session.realms().addClientRole(realm, this, name);
    }

    @Override
    public RoleModel addRole(String id, String name) {
        return session.realms().addClientRole(realm, this, id, name);
    }

    @Override
    public boolean removeRole(RoleModel roleModel) {
        return session.realms().removeRole(realm, roleModel);
    }

    @Override
    public Set<RoleModel> getRoles() {
        return session.realms().getClientRoles(realm, this);
    }

    @Override
    public boolean hasScope(RoleModel role) {
        if (isFullScopeAllowed()) return true;
        Set<RoleModel> roles = getScopeMappings();
        if (roles.contains(role)) return true;

        for (RoleModel mapping : roles) {
            if (mapping.hasRole(role)) return true;
        }
        roles = getRoles();
        if (roles.contains(role)) return true;

        for (RoleModel mapping : roles) {
            if (mapping.hasRole(role)) return true;
        }
        return false;
    }

    @Override
    public List<String> getDefaultRoles() {
        Collection<RoleEntity> entities = entity.getDefaultRoles();
        List<String> roles = new ArrayList<String>();
        if (entities == null) return roles;
        for (RoleEntity entity : entities) {
            roles.add(entity.getName());
        }
        return roles;
    }

    @Override
    public void addDefaultRole(String name) {
        RoleModel role = getRole(name);
        if (role == null) {
            role = addRole(name);
        }
        Collection<RoleEntity> entities = entity.getDefaultRoles();
        for (RoleEntity entity : entities) {
            if (entity.getId().equals(role.getId())) {
                return;
            }
        }
        RoleEntity roleEntity = RoleAdapter.toRoleEntity(role, em);
        entities.add(roleEntity);
    }

    @Override
    public void updateDefaultRoles(String... defaultRoles) {
        // getEntity.invalidate();
        Collection<RoleEntity> entities = entity.getDefaultRoles();
        Set<String> already = new HashSet<String>();
        List<RoleEntity> remove = new ArrayList<>();
        for (RoleEntity rel : entities) {
            if (!contains(rel.getName(), defaultRoles)) {
                remove.add(rel);
            } else {
                already.add(rel.getName());
            }
        }
        for (RoleEntity entity : remove) {
            entities.remove(entity);
        }
        em.flush();
        for (String roleName : defaultRoles) {
            if (!already.contains(roleName)) {
                addDefaultRole(roleName);
            }
        }
        em.flush();
    }

    @Override
    public void removeDefaultRoles(String... defaultRoles) {
        Collection<RoleEntity> entities = entity.getDefaultRoles();
        List<RoleEntity> remove = new ArrayList<RoleEntity>();
        for (RoleEntity rel : entities) {
            if (contains(rel.getName(), defaultRoles)) {
                remove.add(rel);
            }
        }
        for (RoleEntity entity : remove) {
            entities.remove(entity);
        }
        em.flush();
    }




    @Override
    public int getNodeReRegistrationTimeout() {
        return getEntity().getNodeReRegistrationTimeout();
    }

    @Override
    public void setNodeReRegistrationTimeout(int timeout) {
        // getEntity.invalidate();
        entity.setNodeReRegistrationTimeout(timeout);
    }

    @Override
    public Map<String, Integer> getRegisteredNodes() {
        return getEntity().getRegisteredNodes();
    }

    @Override
    public void registerNode(String nodeHost, int registrationTime) {
        Map<String, Integer> currentNodes = getRegisteredNodes();
        currentNodes.put(nodeHost, registrationTime);
        em.flush();
    }

    @Override
    public void unregisterNode(String nodeHost) {
        Map<String, Integer> currentNodes = getRegisteredNodes();
        currentNodes.remove(nodeHost);
        em.flush();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || !(o instanceof ClientModel)) return false;

        ClientModel that = (ClientModel) o;
        return that.getId().equals(getId());
    }

    @Override
    public int hashCode() {
        return getId().hashCode();
    }

    public String toString() {
        return getClientId();
    }

}
