package com.rera.mss.security

import com.fasterxml.jackson.annotation.JsonIgnore
import com.rera.mss.model.User
import com.rera.mss.model.UserRole
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UserDetails

class UserPrincipal(private var id: Long,
                    private var firstName: String,
                    private var lastName: String,
                    private var username: String,

                    @JsonIgnore
                    private var email: String,

                    @JsonIgnore
                    private var password: String,

                    private var authorities: Collection<GrantedAuthority>
) : UserDetails {

    fun getId(): Long {
        return id
    }

    fun getFirstName(): String {
        return firstName
    }

    fun getLastName(): String {
        return lastName
    }

    fun getEmail(): String {
        return email
    }

    override fun getUsername(): String {
        return username
    }


    override fun getPassword(): String {
        return password
    }

    override fun getAuthorities(): Collection<GrantedAuthority> {
        return authorities
    }


    override fun isEnabled(): Boolean {
        return true
    }

    override fun isCredentialsNonExpired(): Boolean {
        return true
    }

    override fun isAccountNonExpired(): Boolean {
        return true
    }

    override fun isAccountNonLocked(): Boolean {
        return true
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as UserPrincipal

        if (id != other.id) return false

        return true
    }

    override fun hashCode(): Int {
        return id.hashCode()
    }

    companion object {
        fun create(user: User): UserPrincipal {
            val authorities: List<GrantedAuthority> = user.userRoles.map { userRole: UserRole ->
                SimpleGrantedAuthority(userRole.role.name.toString())
            }
            return UserPrincipal(
                    id = user.id,
                    firstName = user.firstName,
                    lastName = user.lastName,
                    username = user.username,
                    email = user.email,
                    password = user.password,
                    authorities = authorities
            )
        }
    }
}