package com.zsc.bill.framework.security;

import com.zsc.bill.modules.system.entity.Authority;
import com.zsc.bill.modules.system.entity.Dept;
import com.zsc.bill.modules.system.entity.Role;
import com.zsc.bill.modules.system.entity.User;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
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 enabled;
    public String nickName ;

    public Dept dept;
    public Role role;
    public Set<SimpleGrantedAuthority> authorities;

    public UserDetailsImpl(Long id, String username, String password, String nickName, Boolean enabled, Dept dept, Role role, Set<Authority> authorities) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.enabled = enabled;
        this.nickName = nickName;
        this.dept = dept;
        this.role = role;
        this.authorities = authorities.stream().map(authority -> new SimpleGrantedAuthority(authority.getName())).collect(Collectors.toSet());;


    }


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

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

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

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

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

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

}

