package com.izouma.nineth.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.izouma.nineth.domain.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;
import java.util.Optional;

/**
 * Created by stephan on 20.03.16.
 */
public class JwtUser implements UserDetails {

    private static final long serialVersionUID = 5803985158027956021L;

    private final Collection<? extends GrantedAuthority> authorities;
    private final Date                                   lastPasswordResetDate;
    private final User                                   user;

    public JwtUser(User user, Collection<? extends GrantedAuthority> authorities) {
        this.authorities = authorities;
        this.lastPasswordResetDate = Date.from(user.getCreatedAt().atZone(ZoneId.systemDefault()).toInstant());
        this.user = user;
    }

    @JsonIgnore
    public Long getId() {
        return user.getId();
    }

    @Override
    public String getUsername() {
        return Optional.ofNullable(user.getId()).map(Object::toString).orElse(null);
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

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

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public boolean isEnabled() {
        return !user.isDel();
    }

    @JsonIgnore
    public Date getLastPasswordResetDate() {
        return lastPasswordResetDate;
    }

    public User getUser() {
        return user;
    }
}
