package com.eactive.httpmockserver.common.security;

import com.eactive.httpmockserver.user.entity.StaffUser;
import com.eactive.httpmockserver.user.entity.User;
import com.eactive.httpmockserver.user.service.UserService;
import com.eactive.httpmockserver.common.exception.NotFoundException;
import com.eactive.httpmockserver.common.exception.UserNotLoginException;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.InvocationTargetException;

public class CurrentUserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(CurrentUser.class) != null &&
                parameter.getParameterType().equals(StaffUser.class);
    }

    @Override
    @Transactional
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        Authentication authentication = (Authentication) webRequest.getUserPrincipal();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new UserNotLoginException();
        }
        StaffUser user = null;
        try {
            user = userService.findByEsntlId((String) PropertyUtils.getProperty(authentication.getPrincipal(), "esntlId"));
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new NotFoundException("User not found");
        }

        if (user == null) throw new UserNotLoginException();
        return user;
    }
}
