package com.chenyang.nse.bussiness.kms.controller;

import com.chenyang.nse.bussiness.kms.model.Kms;
import com.chenyang.nse.bussiness.kms.service.KmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"kms"})
public class PlainKeyController {
   protected Logger logger = LoggerFactory.getLogger(this.getClass());
   @Autowired
   protected KmsService kmsService;

   @RequestMapping({"plainkey"})
   public String plainKey(@RequestParam(required = false) String datakey) {
      this.logger.info("datakey=[{}]", datakey);
      if (!StringUtils.hasText(datakey)) {
         return "datakey is required";
      } else {
         try {
            return this.kmsService.obtainSecretKey(Kms.MasterKey.getInstance().getKeyid(), this.kmsService.obtainAccessToken(this.kmsService.obtainChallengeCode()), datakey);
         } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
            return String.format("[%s]%s", e.getClass().getName(), e.getMessage());
         }
      }
   }
}
