package org.gcube.application.cms.plugins.implementations;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.gcube.application.cms.serialization.Serialization;
import org.gcube.application.geoportal.common.model.document.accounting.User;
import org.gcube.application.geoportal.common.model.rest.ConfigurationException;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.HandlerDeclaration;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class RoleManager {

    HashMap<String,StepAccess> accessMap=new HashMap<>();


    public RoleManager(HandlerDeclaration config) throws ConfigurationException {
        List l =config.getConfiguration().get("step_access", List.class);
        if(l==null|| l.isEmpty()) throw new ConfigurationException("Missing Role management in UCD");
        for (Object o : l) {
            StepAccess a= Serialization.convert(o, StepAccess.class);
            accessMap.put(a.getStepId(),a);
        }
    }

    public boolean canInvokeStep(String stepID,User u) throws ConfigurationException {
        if(!accessMap.containsKey(stepID)) throw new ConfigurationException("Missing step "+stepID+" access definition");

        List<String> roles=accessMap.get(stepID).getRoles();
        if(roles.isEmpty()) return true;

        for (String role : roles)
            if (u.getRoles().contains(role))
                return true;

        return false;
    }

    @XmlRootElement
    @AllArgsConstructor
    @Getter
    @Setter
    @ToString(callSuper = true)
    public static class StepAccess {

        public static final String STEP="STEP";
        public static final String ROLES="roles";


        @JsonProperty(STEP)
        private String stepId;

        @JsonProperty(ROLES)
        private List<String> roles;
    }
}
