package org.iri_research.renkan.models;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import org.iri_research.renkan.Constants;
import org.joda.time.LocalDate;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

@Document(collection = "users")
public class User extends AbstractRenkanModel<String> implements UserDetails {
    
    public static class UserComparator implements Comparator<User> {

        @Override
        public int compare(User u1, User u2) {
            if(u1 == null || u1.getId() == null) {
                return (u2==null || u2.getId() == null)? 0 : Integer.MIN_VALUE;
            }
            else {
                return u2==null?Integer.MAX_VALUE:u1.getId().compareTo(u2.getId());
            }
            
        }
        
    }

    private static final long serialVersionUID = 6972038893086220548L;
    
    
    private String avatar;
    @Field("credentials_expiration_date")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "GMT")
    private LocalDate credentialsExpirationDate;
    private String email;
    private boolean enabled;
    @Field("expiration_date")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "GMT")
    private LocalDate expirationDate;
    private boolean locked;
    private String password;
    @Field("authorities")
    private List<String> userAuthorities;
    
    private Set<String> groups = new TreeSet<>();

    public User() {
    }

    public User(String id, String title, String description, String uri,
            String color) {
        super(id, title, description, uri, color);
        if(this.id == null) {
            this.id = Constants.UUID_GENERATOR.generate().toString();
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        boolean hasUserRole = false;
        for (String role : this.getUserAuthorities()) {
            hasUserRole = hasUserRole || Constants.ROLE_USER.equals(role);
            authorities.add(new SimpleGrantedAuthority(role));
        }
        if(!hasUserRole) {
            authorities.add(new SimpleGrantedAuthority(Constants.ROLE_USER));
        }
        
        return authorities;
    }

    public String getAvatar() {
        return avatar;
    }

    public String getColor() {
        return this.color;
    }

    public LocalDate getCredentialsExpirationDate() {
        return credentialsExpirationDate;
    }

    public String getEmail() {
        return email;
    }

    public LocalDate getExpirationDate() {
        return expirationDate;
    }

    @Override
    @JsonIgnore
    public String getPassword() {
        return this.password;
    }

    @Override
    protected String getRawKeyPart() {
        return this.id;
    }

    public List<String> getUserAuthorities() {
        return userAuthorities;
    }

    @Override
    @JsonIgnore
    public String getUsername() {
        return this.title;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.expirationDate == null
                || this.expirationDate.isAfter(LocalDate.now());
    }

    @Override
    public boolean isAccountNonLocked() {
        return !this.locked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.credentialsExpirationDate == null
                || this.credentialsExpirationDate.isAfter(LocalDate.now());
    }

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

    public boolean isLocked() {
        return locked;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    public void setCredentialsExpirationDate(LocalDate credentialsExpirationDate) {
        this.credentialsExpirationDate = credentialsExpirationDate;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public void setExpirationDate(LocalDate expirationDate) {
        this.expirationDate = expirationDate;
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUserAuthorities(List<String> userAuthorities) {
        this.userAuthorities = userAuthorities;
    }

    public Set<String> getGroups() {
        if(this.groups == null) {
            this.groups = new TreeSet<>();
        }
        return groups;
    }
    
    
    public boolean addGroup(Group g) {
        return this.addGroup(g.getId());
    }

    public boolean addGroup(String groupId) {
        return this.getGroups().add(groupId);
    }

    public boolean removeGroup(Group g) {
        return this.removeGroup(g.getId());
    }
    
    public boolean removeGroup(String groupId) {
        return (this.groups == null)?false:this.groups.remove(groupId);
    }
    
    @Override
    protected String getDefaultId() {
        return UUID.randomUUID().toString();
    }

}
