package security.resolvers;

import common.model.User;
import common.repository.UserRepository;
import exception.TransferCurrentAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
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 security.annotation.CurrentAccount;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by nolan on 11/11/2016.
 * description:
 */

@Component
public class LoginUserMethodArgumentsResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private UserRepository accountRepository;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(User.class) && parameter.hasParameterAnnotation(CurrentAccount.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest nativeRequest = (HttpServletRequest) webRequest.getNativeRequest();
        Object currentAct = nativeRequest.getSession().getAttribute("$CURRENT_ACCOUNT$");
        if (currentAct != null) {
            return currentAct;
        }
        throw new TransferCurrentAccountException();
    }
}
