package incheon.sgp.drm.service.impl;

import incheon.ags.drm.vo.DrmContentVO;
import incheon.ags.drm.vo.DrmPoiVO;
import incheon.ags.mrb.analysis.web.SpatialAnalysisController;
import incheon.cmm.g2f.layer.vo.TaskLayerSearchRequestDTO;
import incheon.cmm.g2f.layer.vo.TaskLayerVO;
import incheon.sgp.drm.mapper.sgpDrmMapper;
import incheon.sgp.drm.service.sgpDrmService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("sgpDrmService")
@RequiredArgsConstructor
public class sgpDrmServiceImpl extends EgovAbstractServiceImpl implements sgpDrmService {

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

    // OS별 절대 경로 주입
    @Value("${drm.upload.base-path.win}")
    private String winFilePath;
    @Value("${drm.upload.base-path.linux}")
    private String linuxFilePath;

    @Override
    public List<TaskLayerVO> getLayerList(TaskLayerSearchRequestDTO searchVO) throws Exception {
        return sgpDrmMapper.getLayerList(searchVO);
    }
    @Override
    public List<Map<String, Object>> getAddressByPoint(String pnu) throws Exception {
        return sgpDrmMapper.getAddressByPoint(pnu);
    }

    /* DRM_POI */
    @Override
    public List<DrmPoiVO> selectPOIList(DrmPoiVO drmPoiVO) throws Exception {
        return sgpDrmMapper.selectPOIList(drmPoiVO);
    }
    @Override
    public int selectPOIListCnt(DrmPoiVO drmPoiVO) throws Exception {
        return sgpDrmMapper.selectPOIListCnt(drmPoiVO);
    }
    @Override
    public DrmPoiVO searchPoiDetail(DrmPoiVO drmPoiVO) throws Exception {
        return sgpDrmMapper.searchPoiDetail(drmPoiVO);
    }

    /* CONTENT */
    @Override
    public List<DrmContentVO> selectContentList(DrmContentVO drmContentVO) throws Exception {
        return sgpDrmMapper.selectContentList(drmContentVO);
    }
    public int selectContentListCnt(DrmContentVO drmContentVO) throws Exception {
        return sgpDrmMapper.selectContentListCnt(drmContentVO);
    }
    @Override
    public DrmContentVO searchContentDetail(Long contsId) throws Exception {
        return sgpDrmMapper.searchContentDetail(contsId);
    }

    /**
     * OS에 따라 저장 경로 결정
     */
    private String getOsDependentBasePath() {
        String rawOsName = System.getProperty("os.name");
        String osName = (rawOsName != null) ? rawOsName.toLowerCase() : "linux";
        if (osName.contains("win")) {
            return this.winFilePath;
        } else {
            return this.linuxFilePath;
        }
    }

    /**
     * 관리시스템 - 콘텐츠 분류에따라 읽어오거나 저장할 첨부파일 경로 결정
     * @param clsf 콘텐츠 분류
     * @param fileNm 파일명
     */
    public Path getFilePath (String clsf, String fileNm) throws Exception {

        // OS에 따라 baseDir 문자열을 획득
        String baseDirString = getOsDependentBasePath();
        Path baseDir = Paths.get(baseDirString);

        // 분류에 따른 하위 폴더 경로 설정
        String subPath = switch (clsf) {
            case "CNT000" -> "ags/drm/content/cnt000";
            case "CNT001" -> "ags/drm/content/cnt001";
            case "CNT002" -> "ags/drm/content/cnt002";
            case "CNT003" -> "ags/drm/content/cnt003";
            case "CNT004" -> "ags/drm/content/cnt004";
            default -> "ags/drm/content/etc";
        };

        /* 저장 디렉토리 경로 생성 */
        // baseDir (절대 경로)와 subPath를 결합합니다. (OS 독립적)
        Path dirPath = baseDir.resolve(subPath);

        // 디렉토리 생성
        if (!Files.exists(dirPath)) {
            Files.createDirectories(dirPath);
        }

        // 최종 파일 경로 반환
        return dirPath.resolve(fileNm);
    }
    /**
     * 스카이 드론 - 콘텐츠 분류에따라 읽어올 첨부파일 저장경로 결정
     * @param clsf 콘텐츠 분류
     * @param fileNm 파일명
     */
    public Path getSgpFilePath (String clsf, String fileNm) throws Exception {

        String baseDirString = getOsDependentBasePath();
        Path baseDir = Paths.get(baseDirString);

        String subPath = switch (clsf) {
            case "CNT000" -> "sgp/drm/content/cnt000";
            case "CNT001" -> "sgp/drm/content/cnt001";
            case "CNT002" -> "sgp/drm/content/cnt002";
            case "CNT003" -> "sgp/drm/content/cnt003";
            case "CNT004" -> "sgp/drm/content/cnt004";
            default -> "sgp/drm/content/etc";
        };

        Path dirPath = baseDir.resolve(subPath);

        if (!Files.exists(dirPath)) {
            Files.createDirectories(dirPath);
        }

        return dirPath.resolve(fileNm);
    }
}
