package com.dxhy.auth.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.dxhy.auth.config.KeyConfiguration;
import com.dxhy.auth.service.AuthClientService;
import com.dxhy.common.msg.BaseResponse;
import com.dxhy.common.msg.ObjectRestResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang
 * @date 2019年3月26日 下午5:54:24
 *
 */
@RestController
@RequestMapping("client")
@Slf4j
public class ClientController {
    @Resource
    private AuthClientService authClientService;
    @Resource
    private KeyConfiguration keyConfiguration;

    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public ObjectRestResponse<String> getAccessToken(String clientId, String secret) throws Exception {
        String apply = authClientService.apply(clientId, secret);
        if (StringUtils.isNoneBlank(apply)) {
            return new ObjectRestResponse<String>().data(apply);
        } else {
            BaseResponse baseRes = new BaseResponse();
            baseRes.setCode(40301);
            baseRes.setMsg("Client not found or Client secret is error!");
            return new ObjectRestResponse<String>().data(JSON.toJSONString(baseRes));
        }
    }

    @RequestMapping(value = "/myClient")
    public ObjectRestResponse<List<String>> getAllowedClient(String serviceId, String secret) {
        List<String> allowedClient = authClientService.getAllowedClient(serviceId, secret);
        return new ObjectRestResponse<List<String>>().data(allowedClient);
    }

    @RequestMapping(value = "/servicePubKey", method = RequestMethod.POST)
    public ObjectRestResponse<byte[]> getServicePublicKey(@RequestParam("clientId") String clientId,
        @RequestParam("secret") String secret) {
        byte[] servicePubKey = keyConfiguration.getServicePubKey();
        return new ObjectRestResponse<byte[]>().data(servicePubKey);
    }

    @RequestMapping(value = "/userPubKey", method = RequestMethod.POST)
    public ObjectRestResponse<byte[]> getUserPublicKey(@RequestParam("clientId") String clientId,
        @RequestParam("secret") String secret) {
        byte[] userPubKey = keyConfiguration.getUserPubKey();
        return new ObjectRestResponse<byte[]>().data(userPubKey);
    }

}
