package incheon.cmm.g2f.download.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import incheon.cmm.g2f.download.service.G2FDownloadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import incheon.cmm.g2f.layer.vo.TaskLayerVO;
import incheon.cmm.g2f.layer.vo.userLayerSearchRequestDTO;
import incheon.com.cmm.api.DefaultApiResponse;

@Controller
@RequestMapping("/cmm/g2f/download")
public class DownloadController {

    private static final Logger logger = LoggerFactory.getLogger(DownloadController.class);

    private final G2FDownloadService downloadService;

    @Autowired
    public DownloadController(G2FDownloadService downloadService) {
        this.downloadService = downloadService;
    }

    @GetMapping("/download.do")
    public String download() {
        return "/cmm/g2f/basemap/download/download";
    }

    /**
     *  @GetMapping("/downloadFile")
     */
    @GetMapping("/downloadFile")
    @ResponseBody
    public ResponseEntity<Resource> download(
            @RequestParam Long layerId,
            @RequestParam String format,
            @RequestParam(required = false) String columns,
            @RequestParam(name = "layerType", defaultValue = "USER") String layerType) {

        try {
            return downloadService.download(layerId, layerType, format, columns);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 다운로드 가능한 레이어 정보 조회
     */
    @GetMapping("/info")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getDownloadInfo(@RequestParam Long layerId) {
        Map<String, Object> response = new HashMap<>();

        try {
            Map<String, Object> layerInfo = downloadService.getDownloadInfo(layerId);
            response.put("success", true);
            response.put("layerInfo", layerInfo);
            response.put("supportedFormats", downloadService.getSupportedFormats(layerId));
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            logger.error(e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        }  catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.put("success", false);
            response.put("message", "레이어 정보 조회 실패");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 레이어 다운로드 가능 여부 체크
     */
    @GetMapping("/check")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> checkDownloadable(@RequestParam Long layerId) {
        Map<String, Object> response = new HashMap<>();

        try {
            Map<String, Object> layerInfo = downloadService.getDownloadInfo(layerId);
            boolean downloadable = layerInfo != null && layerInfo.get("lyrsrvcnm") != null;

            response.put("success", true);
            response.put("downloadable", downloadable);
            response.put("layerId", layerId);

            if (downloadable) {
                response.put("layerName", layerInfo.get("tasklyrnm"));
                response.put("spaceType", layerInfo.get("spcety"));
            }

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            logger.error(e.getMessage(), e);
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.put("success", false);
            response.put("downloadable", false);
            response.put("message", "레이어 다운로드 가능 여부 체크 실패");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 사용자 레이어 리스트
     */
    @GetMapping("/user")
    public ResponseEntity<DefaultApiResponse<Map<String, Object>>> getUserayerList(
            userLayerSearchRequestDTO searchVO) {

        if (searchVO.getPageIndex() < 1) {
            searchVO.setPageIndex(1);
        }

        List<TaskLayerVO> content = downloadService.selectUserLayerListTot(searchVO);

        Map<String, Object> response = new HashMap<>();
        response.put("content", content);

        if (searchVO.getPageSize() > 1) {
            long total = downloadService.selectUserLayerListTotCnt(searchVO);
            response.put("page", searchVO.getPageIndex());
            response.put("size", searchVO.getPageSize());
            response.put("totalElements", total);
            response.put("totalPages", (int) Math.ceil((double) total / searchVO.getPageSize()));
        }

        return ResponseEntity.ok(DefaultApiResponse.success(response));
    }
}
