/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.csu.sdmx.web.security;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Table;
import org.hibernate.annotations.CollectionOfElements;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

/**
 *
 * @author themi
 */
@Entity
@Table(name = "SDMX_USERS")
public class User implements Serializable{
    public static final String SEPARATOR = ";";
    
    @Id
    private String personalNumber;
    
    @CollectionOfElements(fetch = FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    @Enumerated(EnumType.STRING)
    @JoinTable(
         name="SDMX_USER_PERMISSIONS",
         joinColumns=@JoinColumn(name="personalNumber")
    )
    private List<Permission> permissions;
    
    @CollectionOfElements(fetch = FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    @JoinTable(
         name="SDMX_USER_URNS",
         joinColumns=@JoinColumn(name="personalNumber")
    )
    private List<String> allowedUrns;

    public User() {
        permissions = new ArrayList<>();
        allowedUrns = new ArrayList<>();
    }

    public User(String ident) {
        this();
        this.personalNumber = ident;
    }

    public boolean hasPermission(Permission permission){
        return permissions.contains(permission);
    }

    public boolean hasUrn(String urn){
        for(String allowedUrn : allowedUrns){
            if(urn.contains(allowedUrn))
                return true;
        }
        
        if(allowedUrns.contains("*"))
            return true;
        
        return false;
    }

    public String getPersonalNumber() {
        return personalNumber;
    }

    public void setPersonalNumber(String personalNumber) {
        this.personalNumber = personalNumber;
    }

    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }

    public List<String> getAllowedUrns() {
        return allowedUrns;
    }

    public void setAllowedUrns(List<String> allowedUrns) {
        this.allowedUrns = allowedUrns;
    }
}
