package com.inspect.common.security.utils;

import com.inspect.base.core.constant.SecurityConstants;
import com.inspect.base.core.context.SecurityContextHolder;
import com.inspect.base.core.utils.ServletUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.system.base.model.LoginUser;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class SecurityUtils {
    public static Long getUserId() {
        return SecurityContextHolder.getUserId();
    }

    public static String getUsername() {
        return SecurityContextHolder.getUserName();
    }

    public static String getUserKey() {
        return SecurityContextHolder.getUserKey();
    }

    public static LoginUser getLoginUser() {
        return SecurityContextHolder.get(SecurityConstants.LOGIN_USER, LoginUser.class);
    }

    public static String getToken() {
        return getToken(ServletUtils.getRequest());
    }

    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        return replaceTokenPrefix(token);
    }

    public static String replaceTokenPrefix(String token) {
        if (StringUtils.isNotEmpty(token) && token.startsWith("Bearer ")) {
            token = token.replaceFirst("Bearer ", "");
        }

        return token;
    }

    public static boolean isAdmin(Long userId) {
        return userId != null && 1L == userId.longValue();
    }

    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    public static void main(String[] args) {
        boolean b = matchesPassword("e6e061838856bf47e1de730719fb2609", "$2a$10$d48RQj1fykHGbu9S14iDWuq9KelaOU.erPSIm0tRzYLHu0mMCGdyO");
        System.out.println(b);
        System.out.println(encryptPassword("e6e061838856bf47e1de730719fb2609"));
    }
}
