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

import com.chenyang.nse.bussiness.thkms.service.ThKmsService;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ThKmsController {
   protected Logger logger = LoggerFactory.getLogger(this.getClass());
   @Autowired
   protected ThKmsService thKmsService;

   @RequestMapping({"/chiron/v1/system/createKey"})
   public String createKey() {
      try {
         String keyId = this.thKmsService.createKey();
         this.logger.info(keyId);
         return keyId;
      } catch (Exception e) {
         this.logger.error(e.getMessage(), e);
         return e.getMessage();
      }
   }

   @RequestMapping({"/chiron/v1/system/generateDataKey"})
   public String generateDataKey() {
      try {
         String cipherDataKey = this.thKmsService.generateDataKey();
         this.logger.info(cipherDataKey);
         return cipherDataKey;
      } catch (Exception e) {
         this.logger.error(e.getMessage(), e);
         return e.getMessage();
      }
   }

   @RequestMapping({"/chiron/v1/system/decryptDataKeyByPubKey"})
   public String decryptDataKeyByPubKey(HttpServletRequest request) {
      try {
         String cipherDataKey = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
         String sm4Key = this.thKmsService.decryptDataKey(cipherDataKey);
         this.logger.info(sm4Key);
         return sm4Key;
      } catch (Exception e) {
         this.logger.error(e.getMessage(), e);
         return e.getMessage();
      }
   }
}
