package com.kamco.cd.kamcoback.postgres.core;

import com.kamco.cd.kamcoback.common.utils.FIleChecker;
import com.kamco.cd.kamcoback.mapsheet.dto.ImageryDto;
import com.kamco.cd.kamcoback.postgres.entity.MapSheetMngHstEntity;
import com.kamco.cd.kamcoback.postgres.repository.mapsheet.MapSheetMngFileCheckerRepository;
import com.kamco.cd.kamcoback.postgres.repository.mapsheet.MapSheetMngRepository;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class MapSheetMngFileCheckerCoreService {

  private final MapSheetMngFileCheckerRepository mapSheetMngFileCheckerRepository;
  private final MapSheetMngRepository mapSheetMngRepository;

  private static final String ORIGINAL_IMAGES_PATH = "/app/original-images";

  @Value("{spring.profiles.active}")
  private String activeEnv;

  public ImageryDto.SyncReturn syncProcess(ImageryDto.searchReq searchReq) {
    String flag = "SUCCESS";
    int syncCnt = 0;
    int tfwErrCnt = 0;
    int tifErrCnt = 0;

    // 대상파일목록 가저오기
    Page<ImageryDto.SyncDto> pageImagerySyncDto =
        mapSheetMngFileCheckerRepository.findImagerySyncList(searchReq);

    for (ImageryDto.SyncDto dto : pageImagerySyncDto.getContent()) {

      boolean isTfwFile = true;
      isTfwFile = FIleChecker.checkTfw(dto.getMiddlePath() + dto.getFilename());

      boolean isGdalInfoTiffFile = true;
      isGdalInfoTiffFile = FIleChecker.cmmndGdalInfo(dto.getCogMiddlePath() + dto.getCogFilename());
      // isGdalInfoTiffFile = FIleChecker.cmmndGdalInfo("D:/kamco_cog/36713/36713073_cog.tif");

      syncCnt = syncCnt + 1;
      if (!isTfwFile) tfwErrCnt = tfwErrCnt + 1;
      if (!isGdalInfoTiffFile) tifErrCnt = tifErrCnt + 1;

      // 예: 특정 작업 수행
      // someService.process(dto);
    }

    if (tfwErrCnt > 0 || tifErrCnt > 0) flag = "ERROR";

    return new ImageryDto.SyncReturn(flag, syncCnt, tfwErrCnt, tifErrCnt);
  }

  public Optional<MapSheetMngHstEntity> findHstByUid(Long hstUid) {
    return mapSheetMngRepository.findMapSheetMngHstInfo(hstUid);
  }
}
