package com.eactive.eai.rms.common.cm;

import com.eactive.eai.rms.common.cm.ui.CmLogDetailUI;
import com.eactive.eai.rms.common.cm.ui.CmLogUI;
import com.eactive.eai.rms.common.cm.ui.CmLogUISearch;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.IbatisComboService;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.vo.GridResponse;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

//import com.eactive.eai.rms.ext.kakaocard.cm.KakaoCardCmFlagDao;

@Controller
public class CmLogController extends BaseController {
   
   @Autowired private ComboService comboService;
   @Autowired private CmLogService cmLogService;

   @Autowired
   private IbatisComboService ibatisComboService;

   @GetMapping(value = "/common/acl/cmLog/cmLog.view")
   public String view() {
      return "/common/acl/cmLog/cmLog";
   }

   @GetMapping(value = "/common/acl/cmLog/cmLog.view", params = "cmd=DETAIL")
   public String viewDetail() {
      return "/common/acl/cmLog/cmLogDetail";
   }

//   @PostMapping(value= "/common/acl/cmLog/cmLog.view")
//   public String viewList(HttpServletRequest request, @RequestParam(value = "cmd", required = false ) String cmd) throws Exception {
//      if (cmd == null || "LIST".equals(cmd.toUpperCase())){
//         cmd = "";
//      }else {
//         cmd = CamelCaseUtil.converCamelCase(cmd);
//      }
//      String path = request.getServletPath();
//      return path.split("[.]")[0]+cmd;
//   }
   
   @PostMapping(value= "/common/acl/cmLog/cmLog.json", params = "cmd=LIST_INIT_COMBO")
   public ResponseEntity<Map<String, Object>> initCombo() throws Exception {
      Map<String, Object> resultMap = new HashMap<>();

      resultMap.put("ynCombo", comboService.getFromCode("YN"));
      resultMap.put("serviceTypeCombo", serviceTypeCombo());
      resultMap.put("bzwkNameCombo", ibatisComboService.selectListComboForTable("TSEAICM01", "EAIBZWKDSTCD","BZWKDSTICNAME", "", "EAIBZWKDSTCD"));

      return ResponseEntity.ok(resultMap);
   }
   
   
   private List<Map<String, Object>> serviceTypeCombo() {
      List<DataSourceType> onlineDataSourceTypes = DataSourceTypeManager.getOnlineDataSourceTypes();
      List<Map<String, Object>> comboList = onlineDataSourceTypes.stream().map(d -> new HashMap<String, Object>(){{ put("CODE", d.getName()); put("NAME", d.getName()); }}).collect(Collectors.toList());
      comboList.add(new HashMap<String, Object>() {{put("CODE", "BAT"); put("NAME", "BAT");}});
      comboList.add(new HashMap<String, Object>() {{put("CODE", "BAP"); put("NAME", "BAP");}});
      return comboList;
   }

   @PostMapping(value= "/common/acl/cmLog/cmLog.json", params = "cmd=LIST")
   public ResponseEntity<GridResponse<CmLogUI>> selectList(CmLogUISearch cmLogUISearch, Pageable pageable) throws Exception {

      Page<CmLogUI> page = cmLogService.selectList(cmLogUISearch, pageable);
      return ResponseEntity.ok(new GridResponse<>(page));
   }

   @PostMapping(value= "/common/acl/cmLog/cmLog.json", params = "cmd=LIST_FLAG")
   public @ResponseBody GridResponse<Object> selectListFlag(JsonPageVo pageVo, @RequestParam Map<String, String> paramMap) throws Exception {

//      String commitId = getValueOrEmpty(paramMap.get("pop_searchDeployId"));
//      String serviceType = getValueOrEmpty(paramMap.get("pop_searchServiceType"));
//      Flag flag = StringUtils.isNotBlank(paramMap.get("pop_searchFlag")) ? Flag.valueOf(paramMap.get("pop_searchFlag")) : null;
//
//      DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING));
//
//      PageRequest pageable = PageRequest.of(pageVo.getPage()-1, pageVo.getRows());
//      Page<CmFlagEntity> pageableEntity = null;
//      if(flag == null) {
//         pageableEntity = cmFlagDao.findByCmFlagKeyCommitIdContainingAndCmFlagKeyServiceTypeContaining(commitId, serviceType, pageable);
//      } else {
//         pageableEntity = cmFlagDao.findByCmFlagKeyCommitIdContainingAndCmFlagKeyServiceTypeContainingAndFlag(commitId, serviceType, flag, pageable);
//      }

//      GridResponse<CmFlagEntity> gridResponse = new GridResponse<>();
//      gridResponse.setTotal(pageableEntity.getTotalPages());
//      gridResponse.setPage(pageableEntity.getNumber()+1);
//      gridResponse.setRecords(Long.valueOf(pageableEntity.getTotalElements()).intValue());
//      gridResponse.setRows(pageableEntity.getContent());

//      return gridResponse;
      return new GridResponse<>();
   }
   
   @PostMapping(value = "/common/acl/cmLog/cmLog.json", params = "cmd=LIST_BUCKET")
   public @ResponseBody GridResponse<Map<String, Object>> retriveFiles(@RequestParam Map<String, String> paramMap) {
      
      if (System.getProperty("eai.datasource.type").equals("LOCAL")) {
         GridResponse<Map<String, Object>> localTemp = new GridResponse<Map<String, Object>>() {{setRows(new ArrayList<>());}};
         return localTemp;
      } else {
         GridResponse<Map<String, Object>> bucketFileListGrid = cmLogService.bucketFileList(paramMap);
         return bucketFileListGrid;
      }
   }
   
   final static Pattern pattern = Pattern.compile("[^/]+$");
   
   @PostMapping(value = "/common/acl/cmLog/cmLog.json", params = "cmd=DETAIL_S3_DOWNLOAD")
   public ResponseEntity<Object> downloadFile(String objectKey) {
      
      try {
         String fileName = "";
           Matcher matcher = pattern.matcher(objectKey);
           
           if (matcher.find()) {
              fileName = matcher.group();
           } else {
              fileName = "errorParseFileName";
           }
         
           return ResponseEntity.ok().header("Content-Disposition", "attachment; filename=" + fileName).body(cmLogService.getFileContent(objectKey));
           
      } catch (Exception e) {
         
         logger.error(e);
         return ResponseEntity.internalServerError().contentType(new MediaType("text", "plain", StandardCharsets.UTF_8)).body(e.getMessage());
      }
      
   }

   @PostMapping(value= "/common/acl/cmLog/cmLog.json", params = "cmd=DETAIL")
   public ResponseEntity<GridResponse<CmLogDetailUI>> selectDetailList(CmLogUISearch cmLogUISearch, Pageable pageable) throws Exception {

      Page<CmLogDetailUI> page = cmLogService.selectDetailList(cmLogUISearch, pageable);
//      Map<String, Object> map = cmLogService.selectDetailList(pageVo.getStartNum(), pageVo.getEndNum(), paramMap);

      return ResponseEntity.ok(new GridResponse<>(page));
   }
   
}