package com.uas.account.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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 org.springframework.web.servlet.ModelAndView;

import com.uas.account.entity.App;
import com.uas.account.service.AppService;
import com.uas.account.web.BaseController;
import com.uas.sso.common.encrypt.RSA;

/**
 * @author yingp
 *
 */
@Controller
public class AppManagerController extends BaseController {

	@Autowired
	private AppService appService;

	/**
	 * @return
	 */
	@RequestMapping(value = "/console/app", method = RequestMethod.GET)
	public ModelAndView getPage(ModelMap model) {
		return new ModelAndView("console/app", success(appService.findAllView()));
	}

	/**
	 * 查找全部
	 * 
	 */
	@RequestMapping(value = "/api/app/list", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap findAll() {
		return success(appService.findAllView());
	}

	/**
	 * 查找全部可注册应用
	 * 
	 */
	@RequestMapping(value = "/api/app/public", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap findAllPublic() {
		return success(appService.findAllPublicUseView());
	}

	/**
	 * 查找
	 * 
	 * @param uid
	 */
	@RequestMapping(value = "/api/app/{uid}", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap findOne(@PathVariable("uid") String uid) {
		return success(appService.findOne(uid));
	}

	/**
	 * 更新
	 * 
	 * @param app
	 */
	@RequestMapping(value = "/api/app", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap save(App app) {
		appService.save(app);
		return success();
	}

	/**
	 * 删除
	 * 
	 * @param uid
	 */
	@RequestMapping(value = "/api/app/{uid}", method = RequestMethod.DELETE)
	@ResponseBody
	public ModelMap delete(@PathVariable("uid") String uid) {
		appService.delete(uid);
		return success();
	}

	private static final String sessionPrivateKey = "privateKey";

	/**
	 * 获取密钥对
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/api/secret/generate", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap generateKey() throws Exception {
		Map<String, Object> keyMap = RSA.genKeyPair();
		// 私钥走下载通道
		request.getSession().setAttribute(sessionPrivateKey, RSA.getPrivateKey(keyMap));
		return success(RSA.getPublicKey(keyMap));
	}

	/**
	 * 下载私钥
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/api/secret/private")
	public ResponseEntity<byte[]> downloadKey() throws Exception {
		Object privateKey = request.getSession().getAttribute(sessionPrivateKey);
		if (privateKey != null) {
			return outputStream("privateKey.txt", privateKey.toString().getBytes());
		} else {
			printJson(error("未找到密钥，请重新生成"));
			return null;
		}
	}

}
