/*
 * Copyright 2022 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.map.storage.jpa.authorization.resource.entity;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.Version;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import org.keycloak.models.map.authorization.entity.MapResourceEntity.AbstractMapResourceEntity;
import org.keycloak.models.map.common.DeepCloner;
import org.keycloak.models.map.common.StringKeyConverter;
import org.keycloak.models.map.common.UuidValidator;
import org.keycloak.models.map.storage.jpa.Constants;
import org.keycloak.models.map.storage.jpa.JpaRootVersionedEntity;
import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;


/**
 * There are some fields marked by {@code @Column(insertable = false, updatable = false)}.
 * Those fields are automatically generated by database from json field,
 * therefore marked as non-insertable and non-updatable to instruct hibernate.
 */
@Entity
@Table(name = "kc_authz_resource", uniqueConstraints = {@UniqueConstraint(columnNames = {"realmId", "resourceServerId", "name", "owner"})})
@TypeDefs({@TypeDef(name = "jsonb", typeClass = JsonbType.class)})
public class JpaResourceEntity extends AbstractMapResourceEntity implements JpaRootVersionedEntity {

    @Id
    @Column
    private UUID id;

    //used for implicit optimistic locking
    @Version
    @Column
    private int version;

    @Type(type = "jsonb")
    @Column(columnDefinition = "jsonb")
    private final JpaResourceMetadata metadata;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private Integer entityVersion;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private String realmId;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private UUID resourceServerId;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private String name;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private String type;

    @Column(insertable = false, updatable = false)
    @Basic(fetch = FetchType.LAZY)
    private String owner;

    //TODO starts here
    //possible future optimization: use @OneToMany to avoid reinserting entries after every change, see: https://thorben-janssen.com/hibernate-tips-elementcollection/
    @Column(name = "uri")
    @ElementCollection
    @CollectionTable(name = "kc_authz_resource_uri", joinColumns = @JoinColumn(name = "resource_id", nullable = false))
    private Set<String> uris = new HashSet<>();

    @Column(name = "scope_id")
    @ElementCollection
    @CollectionTable(name = "kc_authz_resource_scope", joinColumns = @JoinColumn(name = "resource_id", nullable = false))
    private Set<UUID> scopeIds = new HashSet<>();
    //TODO ends here

    @OneToMany(mappedBy = "root", cascade = CascadeType.PERSIST, orphanRemoval = true)
    private final Set<JpaResourceAttributeEntity> attributes = new HashSet<>();

    /**
     * No-argument constructor, used by hibernate to instantiate entities.
     */
    public JpaResourceEntity() {
        this.metadata = new JpaResourceMetadata();
    }

    public JpaResourceEntity(DeepCloner cloner) {
        this.metadata = new JpaResourceMetadata(cloner);
    }

    /**
     * Used by hibernate when calling cb.construct from read(QueryParameters) method.
     * It is used to select object without metadata(json) field.
     */
    public JpaResourceEntity(UUID id, int version, Integer entityVersion, String realmId, 
            UUID resourceServerId, String name, String type, String owner) {
        this.id = id;
        this.version = version;
        this.entityVersion = entityVersion;
        this.realmId = realmId;
        this.resourceServerId = resourceServerId;
        this.name = name;
        this.type = type;
        this.owner = owner;
        this.metadata = null;
    }

    public boolean isMetadataInitialized() {
        return metadata != null;
    }

    @Override
    public Integer getEntityVersion() {
        if (isMetadataInitialized()) return metadata.getEntityVersion();
        return entityVersion;
    }

    @Override
    public void setEntityVersion(Integer entityVersion) {
        metadata.setEntityVersion(entityVersion);
    }

    @Override
    public Integer getCurrentSchemaVersion() {
        return Constants.CURRENT_SCHEMA_VERSION_AUTHZ_RESOURCE;
    }

    @Override
    public int getVersion() {
        return version;
    }

    @Override
    public String getId() {
        return id == null ? null : id.toString();
    }

    @Override
    public void setId(String id) {
        String validatedId = UuidValidator.validateAndConvert(id);
        this.id = UUID.fromString(validatedId);
    }

    @Override
    public String getRealmId() {
        if (isMetadataInitialized()) return metadata.getRealmId();
        return realmId;
    }

    @Override
    public void setRealmId(String realmId) {
        metadata.setRealmId(realmId);
    }

    @Override
    public String getName() {
        if (isMetadataInitialized()) return metadata.getName();
        return name;
    }

    @Override
    public void setName(String name) {
        metadata.setName(name);
    }

    @Override
    public String getDisplayName() {
        return metadata.getDisplayName();
    }

    @Override
    public void setDisplayName(String displayName) {
        metadata.setDisplayName(displayName);
    }

    @Override
    public Set<String> getUris() {
        return uris;
    }

    @Override
    public void setUris(Set<String> uris) {
        uris = uris == null ? new HashSet<>() : uris;
        this.uris = uris;
    }

    @Override
    public String getType() {
        if (isMetadataInitialized()) return metadata.getType();
        return type;
    }

    @Override
    public void setType(String type) {
        metadata.setType(type);
    }

    @Override
    public String getIconUri() {
        return metadata.getIconUri();
    }

    @Override
    public void setIconUri(String iconUri) {
        metadata.setIconUri(iconUri);
    }

    @Override
    public String getOwner() {
        if (isMetadataInitialized()) return metadata.getOwner();
        return owner;
    }

    @Override
    public void setOwner(String owner) {
        metadata.setOwner(owner);
    }

    @Override
    public Boolean isOwnerManagedAccess() {
        return metadata.isOwnerManagedAccess();
    }

    @Override
    public void setOwnerManagedAccess(Boolean ownerManagedAccess) {
        metadata.setOwnerManagedAccess(ownerManagedAccess);
    }

    @Override
    public void setResourceServerId(String resourceServerId) {
        metadata.setResourceServerId(resourceServerId);
    }

    @Override
    public String getResourceServerId() {
        if (isMetadataInitialized()) return metadata.getResourceServerId();
        return resourceServerId == null ? null : resourceServerId.toString();
    }

    @Override
    public Set<String> getScopeIds() {
        return scopeIds.stream().map(UUID::toString).collect(Collectors.toSet());
    }

    @Override
    public void setScopeIds(Set<String> scopeIds) {
        scopeIds = scopeIds == null ? new HashSet<>() : scopeIds;
        this.scopeIds = scopeIds.stream()
                .map(StringKeyConverter.UUIDKey.INSTANCE::fromString)
                .collect(Collectors.toSet());
    }

    @Override
    public Map<String, List<String>> getAttributes() {
        Map<String, List<String>> result = new HashMap<>();
        for (JpaResourceAttributeEntity attribute : attributes) {
            List<String> values = result.getOrDefault(attribute.getName(), new LinkedList<>());
            values.add(attribute.getValue());
            result.put(attribute.getName(), values);
        }
        return result;
    }

    @Override
    public void setAttributes(Map<String, List<String>> attributes) {
        this.attributes.clear();
        if (attributes != null) {
            for (Map.Entry<String, List<String>> attrEntry : attributes.entrySet()) {
                setAttribute(attrEntry.getKey(), attrEntry.getValue());
            }
        }
    }

    @Override
    public List<String> getAttribute(String name) {
        return attributes.stream()
                .filter(a -> Objects.equals(a.getName(), name))
                .map(JpaResourceAttributeEntity::getValue)
                .collect(Collectors.toList());
    }

    @Override
    public void setAttribute(String name, List<String> values) {
        removeAttribute(name);
        for (String value : values) {
            JpaResourceAttributeEntity attribute = new JpaResourceAttributeEntity(this, name, value);
            attributes.add(attribute);
        }
    }

    @Override
    public void removeAttribute(String name) {
        attributes.removeIf(attr -> Objects.equals(attr.getName(), name));
    }

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof JpaResourceEntity)) return false;
        return Objects.equals(getId(), ((JpaResourceEntity) obj).getId());
    }
}
