package com.caliverse.admin.global.common.utils;

import com.caliverse.admin.domain.entity.Currencys;
import com.caliverse.admin.domain.entity.Excel;
import com.caliverse.admin.domain.entity.ROUTE;
import com.caliverse.admin.domain.response.IndicatorsResponse;
import com.caliverse.admin.global.common.code.CommonCode;
import com.caliverse.admin.global.common.code.ErrorCode;
import com.caliverse.admin.global.common.exception.RestApiException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Component
public class FileUtils {

    @Value("${excel.file-path}")
    private String filePath;

    public byte[] loadFileByte(String fileName) {
        try {
            String localFilePath = filePath + File.separator + fileName;
            Path sourcePath = Path.of(localFilePath);

            if (!Files.exists(sourcePath)) {
                throw new RuntimeException("파일을 찾을 수 없습니다: " + fileName);
            }

            return Files.readAllBytes(sourcePath);

        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException("파일 로드 중 오류 발생: " + e.getMessage());
        }
    }

    public FileInputStream loadFileStream(String fileName){
        String fullPath = filePath + fileName;

        try (FileInputStream fis = new FileInputStream(new File(fullPath))) {
            return fis;
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

    public File loadFileObject(String fileName){
        String fullPath = filePath + fileName;

        File file = new File(fullPath);

        if (!file.exists() || !file.isFile()) {
            throw new RuntimeException("파일을 찾을 수 없습니다: " + fileName);
        }

        return file;
    }

    public String saveFile(MultipartFile file){
        try{
            String fileName = CommonUtils.setFileName(file.getOriginalFilename());
            String path = filePath + File.separator + fileName;
            Path destinationPath = Path.of(path);

            Files.copy(file.getInputStream(), destinationPath, StandardCopyOption.REPLACE_EXISTING);

            return fileName;
        } catch(Exception e){
            log.error(e.getMessage());
            throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.ERROR_FILE_UPLOAD.getMessage());
        }
    }

    public boolean deleteFile(String fileName) {
        try {
            String path = filePath + File.separator + fileName;
            Path fileToDelete = Path.of(path);

            if (!Files.exists(fileToDelete)) {
                return false;
            }

            return Files.deleteIfExists(fileToDelete);
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RestApiException(CommonCode.ERROR.getHttpStatus(), ErrorCode.ERROR_FILE_DELETE.getMessage());
        }
    }


    public boolean hasDuplicates(List<String> dataList) {
        Set<String> uniqueValues = new HashSet<>();

        for (String value : dataList) {
            if (uniqueValues.contains(value)) {
                return true;
            }
            uniqueValues.add(value);
        }

        return false;
    }

    public static boolean isString32Characters(String input) {
        if (input == null) {
            return false;
        }
        return input.length() == 32;
    }

    public String getContentType(String fileName) {
        String extension = "";
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            extension = fileName.substring(i + 1).toLowerCase();
        }

        switch (extension) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "pdf":
                return "application/pdf";
            case "txt":
                return "text/plain";
            case "html":
                return "text/html";
            case "doc":
                return "application/msword";
            case "docx":
                return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            case "xls":
                return "application/vnd.ms-excel";
            case "xlsx":
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            default:
                return "application/octet-stream"; // 기본 바이너리 타입
        }
    }


}
