package com.bcxin.api.interfaces.rbacs.responses;

import com.bcxin.Infrastructures.entities.OperatorValueType;
import lombok.AccessLevel;
import lombok.Getter;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

@Getter
public class ResourceGetResponse implements Serializable {
    private final String id;
    private final String categoryId;
    private final String name;
    private final String data;
    private final String dataType;
    private final String metaId;
    private final String metaConfig;
    private final String metaData;
    private final OperatorValueType creator;
    private final OperatorValueType lastModifier;
    @Getter(AccessLevel.NONE)
    private boolean hasPermission;
    private final Collection<ResourceGetResponse> children = new ArrayList<>();

    public ResourceGetResponse(String id, String categoryId, String name, String data,
                               String dataType, String metaId,
                               String metaConfig, String metaData,
                               OperatorValueType creator,
                               OperatorValueType lastModifier) {
        this.hasPermission=true;
        this.id = id;
        this.categoryId = categoryId;
        this.name = name;
        this.data = data;
        this.dataType = dataType;
        this.metaId = metaId;
        this.metaConfig = metaConfig;
        this.metaData = metaData;
        this.creator = creator;
        this.lastModifier = lastModifier;
    }

    public static ResourceGetResponse create(String id, String categoryId, String name, String data, String dataType, String metaId, String metaConfig, String metaData,
                                             OperatorValueType creator, OperatorValueType lastModifier) {
        return new ResourceGetResponse(id, categoryId, name, data, dataType, metaId, metaConfig, metaData, creator, lastModifier);
    }

    public void assignChildResource(ResourceGetResponse response) {
        this.getChildren().add(response);
    }


    public void assignPermissionStatus(boolean hasPermission) {
        this.hasPermission = hasPermission;
    }

    public boolean isShow() {
        if (this.hasPermission) {
            return true;
        }

        if (!CollectionUtils.isEmpty(this.getChildren())) {
            return this.getChildren().stream().anyMatch(ix -> ix.isShow());
        }

        return false;
    }
}
