package com.sys.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
import org.apache.oltu.oauth2.client.response.OAuthResourceResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cku.core.RESTResponse;
import com.cku.util.ServletUtils;
import com.cku.util.SysConfig;
import com.sys.service.OAuthServiceImpl;

/**
 * Created by user on 2016/4/27.
 */
@Controller
@RequestMapping("oauth2Client")
public class Oauth2ClientController {
    @Autowired
    private OAuthServiceImpl oAuthService;
    private static String LOCALURL = null;//"http://localhost:8888/";
    private static String SERVICEURL = null;//"http://www.taochongbao.cn:8080/taochongbao/service/";
    private static String CLIENTID = null;//"c1ebe466-1cdc-4bd3-ab69-77c3542b9dee";
    private static String CLIENTSECRET = null;//"d8346ea2-6017-43ed-ad68-19c0f971738b";
    static{
    	LOCALURL = SysConfig.getInstance().getProperty("localurl");
    	SERVICEURL = SysConfig.getInstance().getProperty("serviceurl");
    	CLIENTID = SysConfig.getInstance().getProperty("clientid");
    	CLIENTSECRET = SysConfig.getInstance().getProperty("clientsecret");
    }
    @ResponseBody
    @RequestMapping("getClientId")
    public void getClientId(HttpServletRequest request, HttpServletResponse response) throws OAuthSystemException, IOException {
        RESTResponse result = null;
        try
        {
            result = new RESTResponse("clientId",CLIENTID);
        }
        catch (Exception e)
        {
            result = new RESTResponse(e);
        }
        ServletUtils.writeResponse(response, result);
    }

    //测试方法sendCode
    @RequestMapping("sendCode")
    public ModelAndView sendCode(HttpServletRequest request, HttpServletResponse response) throws OAuthSystemException, IOException {
        OAuthClientRequest oAuthRequest = OAuthClientRequest
                .authorizationLocation(SERVICEURL+"oauth2/authorize.do")
                .setClientId(CLIENTID)
                .setRedirectURI(LOCALURL+"oauth2Client/getAccessToken.do")
                .setResponseType(OAuth.OAUTH_CODE)
                .buildQueryMessage();
        response.sendRedirect(oAuthRequest.getLocationUri());
        return null;
    }
    //手机端回掉地址
    @RequestMapping("getCode")
    public ModelAndView getCode(HttpServletRequest request, HttpServletResponse response) throws OAuthSystemException, IOException {
        ModelAndView mav = new ModelAndView();
        String authCode = request.getParameter(OAuth.OAUTH_CODE);
        if(!StringUtils.isEmpty(authCode)){
            System.out.printf("authCode==="+authCode);
            //mav.setViewName("redirect:/oauth2Client/getAccessToken.do?code="+authCode);
            return mav;
        }
        //不发送oauth请求，交给手机端实现
        OAuthClientRequest oAuthRequest = OAuthClientRequest
                .authorizationLocation(SERVICEURL+"oauth2/authorize.do")
                .setClientId(CLIENTID)
                .setRedirectURI(LOCALURL+"oauth2Client/getCode.do")
                .setResponseType(OAuth.OAUTH_CODE)
                .buildQueryMessage();
        response.sendRedirect(oAuthRequest.getLocationUri());
        return null;
    }


    @RequestMapping("getAccessToken")
    public Object getAccessToken(HttpServletRequest request,HttpServletResponse response) throws OAuthSystemException, OAuthProblemException, IOException {
        ModelAndView mav = new ModelAndView();
        String authCode = request.getParameter(OAuth.OAUTH_CODE);
        if(StringUtils.isEmpty(authCode)){
            mav.setViewName("redirect:/oauth2Client/getCode.do");
            return mav;
        }
        //使用授权码去服务端获取令牌
        //if(oAuthService.checkAuthCode(authCode)){
        //此处应采用XXX方法调用FavAccessTokenController获取返回的值
        OAuthClientRequest oauthRequest = OAuthClientRequest
                .tokenLocation(SERVICEURL+"oauth2/accessToken.do")
                .setGrantType(GrantType.AUTHORIZATION_CODE)
                .setClientId(CLIENTID)
                .setClientSecret(CLIENTSECRET)
                .setRedirectURI(LOCALURL+"oauth2Client/getCode.do")
                .setCode(authCode)
                .buildQueryMessage();
        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
        OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(oauthRequest);
        String accessToken = oAuthResponse.getAccessToken();
        String expiresIn = oAuthResponse.getExpiresIn().toString();
        System.out.printf("accessToken======"+accessToken);
        System.out.printf("expiresIn======"+expiresIn);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            response.getWriter().write("{ \"accessToken\": \""+accessToken+"\", \"expiresIn\": \""+expiresIn+"\" }");
            return null;
       // }
        //mav.setViewName("redirect:/oauth2Client/getUserInfo.do?access_token="+accessToken);
    }

    @RequestMapping("getUserInfo")
    public Object getUserInfo(HttpServletRequest request,HttpServletResponse response) throws OAuthSystemException, OAuthProblemException, IOException {
        ModelAndView mav = new ModelAndView();
        String accessToken = request.getParameter(OAuth.OAUTH_ACCESS_TOKEN);
        if(StringUtils.isEmpty(accessToken)){
            mav.setViewName("redirect:/oauth2Client/getAccessToken.do");
            return mav;
        }

        OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(SERVICEURL+"oauth2/userInfo.do")
                .setAccessToken(accessToken).buildQueryMessage();
        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
        OAuthResourceResponse resourceResponse = oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        response.getWriter().write( resourceResponse.getBody());
        return null;
    }
}
