package ru.kayashov.bar.model.entity;

import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Entity
@Getter
@Setter
public class Visitor implements UserDetails {
    @Id
    private Long id;
    private String name;
    private String lastName;
    private Integer code;
    private String login;
    private String password;
    private LocalDateTime expired;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "visitor")
    private List<Rating> rating;

    @OneToMany(mappedBy = "visitor")
    private List<BarResident> residents;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return residents.stream()
                .filter(BarResident::getActive)
                .map(BarResident::getRole)
                .map(UserRole::getAuthorities)
                .flatMap(Collection::stream)
                .collect(Collectors.toSet());
    }

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

    @Override
    public String getUsername() {
        return id.toString();
    }

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

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

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

    @Override
    public boolean isEnabled() {
        return true;
    }
}
