/** 
 * BoardPreventSqlInjectionAop.java
 * @author 임새미 
 * @since 2016. 10. 19.
 *
 *  	 수정일                     수정자                                       수정내용
 *  -------------	--------	---------------------------
 *  2016. 10. 19. 	    임새미				       최초생성
 * 
 */
package kcg.faics.cmmn.aop;

import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import kcg.faics.cmmn.service.LogService;
import kcg.faics.cmmn.service.MenuService;
import kcg.faics.cmmn.vo.MenuVO;
import kcg.faics.sec.LoginUserVO;
import kcg.faics.sec.UserUtil;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

/**
 * CommonAop.java
 * 
 * @author 임새미
 * @since 2016. 10. 19.
 *
 *        수정일 수정자 수정내용 ------------- -------- --------------------------- 2016.
 *        10. 19. 임새미 최초생성 2016. 11. 10. 임새미 사용자 로그 생성 부분 추가
 * 
 */
@Aspect
@Component
public class CommonAop {

	@Resource(name = "menuService")
	MenuService menuService;

	@Resource(name = "logService")
	LogService logService;

	@Around("execution(* kcg.faics..*Controller.*(..))")
	public Object menuGenerator(final ProceedingJoinPoint thisJoinPoint) throws Throwable {

		HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String loginUrl = "/loginView.do";
		String url = req.getRequestURI();

		if (loginUrl.equals(url)) {
			return thisJoinPoint.proceed();
		}

		LoginUserVO loginUserVO = null;
		try {
			loginUserVO = UserUtil.getMemberInfo();
		} catch (Exception e) {
			//세션정보가 없을 경우 로그인 페이지로 이동.
			if (loginUserVO == null) {			
				return "redirect:" + loginUrl;
			}
		}
		try {
			for (Object obj : thisJoinPoint.getArgs()) {
				if (obj instanceof Model) {
					Model model = (Model) obj;

					MenuVO menuVO = new MenuVO();
					menuVO.setUserId(loginUserVO.getUserid());
					menuVO.setUserType(loginUserVO.getType());
					List<MenuVO> mainMenuList = menuService.selectMainMenuList(menuVO);
					model.addAttribute("mainMenuList", mainMenuList);

					List<MenuVO> topSubMenuList = menuService.selectTopSubMenuList(menuVO);

					model.addAttribute("topSubMenuList", topSubMenuList);

					HashMap<String, Object> menu = new HashMap<String, Object>();

					String subStr = url.substring(1);
					String boardId = "";
					String group = subStr.split("/")[0];
					String onlyUrl = subStr;
					String qryCate = "";
					if (onlyUrl.indexOf("/") > -1) {
						onlyUrl = subStr.substring(onlyUrl.indexOf("/"));
					} else {
						return thisJoinPoint.proceed();
					}
					url = onlyUrl;

					if (req.getParameter("id") != null) {
						boardId = req.getParameter("id");

						switch (boardId) {
						// 외사통계-통계월보는 타이틀을 같이 쓸것이므로 카테고리를 나누지않는다.
						case "stat_bbs":
							break;

						default:
							if (req.getParameter("category") != null
									&& !req.getParameter("category").equals(" ")) {
								qryCate = "category=" + req.getParameter("category");
							}
							break;
						}
					}

					menu.put("url", url);
					menu.put("group", group);
					menu.put("boardId", boardId);
					menu.put("query", qryCate);

					HashMap<String, Object> menuInfo = menuService.getMenuInfo(menu);
					menuVO.setId(((Double)menuInfo.get("id")).intValue());
					menuInfo.put("userId", loginUserVO.getUserid());

					List<MenuVO> currAndHigherMenuList = menuService.selectListWithHigher(menuVO);
					model.addAttribute("currAndHigherMenuList", currAndHigherMenuList);
					model.addAttribute("menu", menuInfo);
					model.addAttribute("subMenu", menuService.getSubmenu(menuInfo));

					addUserLog(req, menu);
				}
			}
		} catch (Exception e) {
			// e.printStackTrace();
		}

    return thisJoinPoint.proceed();
	}

	/**
	 * 사용자 로그를 기록한다.
	 * 
	 * @param req
	 *            Request 객체
	 * @param menu
	 *            메뉴 Map 객체
	 */
	private void addUserLog(final HttpServletRequest req,
			final HashMap<String, Object> menu) {
		LoginUserVO user = (LoginUserVO) req.getSession()
				.getAttribute("userVO");

		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userid", user.getUserid());
		paramMap.put("name", user.getName());
		paramMap.put("userip", user.getIp());
		paramMap.put("place1", user.getPlace1());
		paramMap.put("position", user.getPosition());

		paramMap.put("location1", menu.get("group"));
		paramMap.put("location2", menu.get("url"));
		paramMap.put("location3", req.getRequestURI());

		try {
			logService.insertUserLog(paramMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
