package com.zsc.edu.gateway.framework.security;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.zsc.edu.gateway.common.enums.EnableState;
import com.zsc.edu.gateway.modules.system.entity.Authority;
import com.zsc.edu.gateway.modules.system.entity.Dept;
import com.zsc.edu.gateway.modules.system.entity.Role;
import com.zsc.edu.gateway.modules.system.entity.User;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author harry yao
 */
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@JsonIgnoreProperties("password")
public class UserDetailsImpl implements UserDetails {

    public Long id;
    public String username;
    public String password;
    public Boolean enableState;
    public String name;
    public Dept dept;
    public Role role;
    public Set<Authority> authorities;

    public UserDetailsImpl(Long id, String username, String password, String name, Boolean enableState, Dept dept, Role role, Set<Authority> authorities) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.enableState = enableState;
        this.name = name;
        this.dept = dept;
        this.role = role;
        this.authorities = authorities;
    }

    public static UserDetailsImpl from(User user) {
        return new UserDetailsImpl(
                user.id,
                user.username,
                user.password,
                user.name,
                user.enableState,
                user.dept,
                user.role,
                user.role.authorities
        );
    }

    @Override

    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities.stream().map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toSet());
    }

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

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

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

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

}
