package com.reyun.security.resolvers;

import com.reyun.exception.TransferCurrentAccountException;
import com.reyun.model.Account;
import com.reyun.repository.AccountRepository;
import com.reyun.security.annotation.CurrentAccount;
import com.reyun.util.Constant;
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 javax.servlet.http.HttpServletRequest;

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

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

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Account.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(Constant.CURRENT_ACCOUNT);
        if (currentAct != null) {
            return currentAct;
        }
        throw new TransferCurrentAccountException();
    }
}
