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

import com.chenyang.nse.bussiness.encryptionrule.service.EncryptionRuleService;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EncryptionRuleController {
   protected Logger logger = LoggerFactory.getLogger(this.getClass());
   @Autowired
   protected EncryptionRuleService encryptionRuleService;

   @RequestMapping({"/encryption.properties"})
   public void export(@RequestParam(required = false,defaultValue = "false") String pretty, HttpServletResponse response) throws IOException {
      try {
         this.logger.info("pretty={}", pretty);
         boolean isPretty = Boolean.valueOf(pretty);
         this.logger.info("isPretty={}", isPretty);
         String encryptionRule = this.encryptionRuleService.obtainEncryptionRule(isPretty);
         byte[] encryptionRuleBytes = encryptionRule.getBytes(StandardCharsets.UTF_8);
         response.setContentType("application/json");
         response.addHeader("Content-Disposition", "attachment; filename=encryption.properties");
         response.setContentLength(encryptionRuleBytes.length);
         response.getOutputStream().write(encryptionRuleBytes);
      } catch (Exception e) {
         this.logger.error(e.getMessage(), e);
         e.printStackTrace(response.getWriter());
      }

   }
}
