package com.mall.sso.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mall.common.dto.MallResult;
import com.mall.common.utils.ExceptionUtil;
import com.mall.sso.service.LoginService;

@Controller
public class LoginController {

	private final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private LoginService loginService;
	
	@RequestMapping(value="/user/login", method=RequestMethod.POST)
	@ResponseBody
	public MallResult login(String username,
			String password,
			HttpServletRequest request,
			HttpServletResponse response) {
		try {
			return loginService.login(username, password, request, response);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return MallResult.build(500, ExceptionUtil.getStackTrace(e));
		}
	}
	
	@RequestMapping("/user/token/{token}")
	@ResponseBody
	public Object getUserByToken(@PathVariable String token,
			String callback) {
		try {
			MallResult result = loginService.getUserByToken(token);
			if (StringUtils.isNotBlank(callback)) {
				MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
				mappingJacksonValue.setJsonpFunction(callback);
				return mappingJacksonValue;
			}
			
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return MallResult.build(500, ExceptionUtil.getStackTrace(e));
		}	
	}
	
	@RequestMapping(value="/user/logout")
	@ResponseBody
	public Object login(HttpServletRequest request,
			HttpServletResponse response,
			String callback) {
		try {
			
			MallResult result = loginService.logout(request, response);
			
			if (StringUtils.isNotBlank(callback)) {
				MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
				mappingJacksonValue.setJsonpFunction(callback);
				return mappingJacksonValue;
			}
			return result;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return MallResult.build(500, ExceptionUtil.getStackTrace(e));
		}
	}
}
