package com.sys.controller;

import com.alibaba.druid.util.StringUtils;
import com.cab.model.User;
import com.cab.service.UserServiceImpl;
import com.sys.service.OAuthServiceImpl;
import com.sys.service.Oauth2ClientServiceImpl;

import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ResponseType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

/**
 * Created by user on 2016/4/27.
 */
@Controller
@RequestMapping("oauth2")
public class Oauth2AuthorizeController {
    @Autowired
    private OAuthServiceImpl oAuthService;
    @Autowired
    private Oauth2ClientServiceImpl oauth2ClientService;
    @Autowired
    UserServiceImpl userService;

    @RequestMapping("authorize")
    public Object authorize(Model model,HttpServletRequest request) throws OAuthSystemException, OAuthProblemException {
        ModelAndView mav = new ModelAndView();
//		String username, String webKey, String scope, String state,String display
        //构建OAuth请求
        OAuthAuthzRequest oAuthzRequest = new OAuthAuthzRequest(request);
        //获取OAuth客户端Id
        String clientId = oAuthzRequest.getClientId();
        //校验客户端Id是否正确
        if(!oAuthService.checkClientId(clientId)){
            OAuthResponse oAuthResponse = OAuthASResponse
                    .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                    .setErrorDescription("无效的客户端Id")
                    .buildJSONMessage();
//			mav.addObject("OAuth2FailedMessage", "无效的客户端Id");
//			mav.setViewName("forward:/oauth2/authorizefailed");
//			return mav;
			return new ResponseEntity(oAuthResponse.getBody(), HttpStatus.valueOf(oAuthResponse.getResponseStatus()));
        }
        //用户信息
        String userInfo = "";
        //TODO 跳转登录页面
        User user = login(request);
        if(user==null) {//登录失败时跳转到登陆页面
        	model.addAttribute("client", oauth2ClientService.selectByClientId(oAuthzRequest.getClientId()));
            return "oauth2login";
        }else{
        	userInfo = user.toOauthString();
        }
        

        //生成授权码
        String authCode = null;
        String responseType = oAuthzRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
        //ResponseType仅支持CODE和TOKEN
        if(responseType.equals(ResponseType.CODE.toString())){
            OAuthIssuerImpl oAuthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
            authCode = oAuthIssuerImpl.authorizationCode();
            oAuthService.addAuthCode(authCode, userInfo);
        }

        //构建OAuth响应
        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);

        //设置授权码
        builder.setCode(authCode);

        //获取客户端重定向地址
        String redirectURI = oAuthzRequest.getParam(OAuth.OAUTH_REDIRECT_URI);

        //构建响应
        OAuthResponse response = builder.location(redirectURI).buildBodyMessage();
        //根据OAuthResponse返回ResponseEntity响应
        HttpHeaders headers = new HttpHeaders();
        try {
            headers.setLocation(new URI(response.getLocationUri()));
//			return new ResponseEntity<>(headers, HttpStatus.valueOf(response.getResponseStatus()));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        mav.addObject(OAuth.OAUTH_CODE, authCode);
        mav.setViewName("redirect:"+redirectURI);
        return mav;
    }
    //TODO存储用户信息
    private User login(HttpServletRequest request) {
        if("get".equalsIgnoreCase(request.getMethod())) {
            return null;
        }
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return null;
        }
        try {
        	UUID dynamic = UUID.randomUUID();
            String md5 = com.cku.util.MD5Generator.generate(password + dynamic.toString());
            User user = userService.login(username, md5, dynamic.toString());
            if(user==null){
            	throw new Exception();
            }
            return user;
        } catch (Exception e) {
            request.setAttribute("error", "登录失败:" + e.getClass().getName());
            return null;
        }
    }
}
