package ru.nbch.credit_tracker.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class CTUtil {

    private static final DateTimeFormatter onlineReportDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH-mm-ss");
    private static final DateTimeFormatter responseReportDateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");


    public static LocalDateTime parseDateFromReportFileName(String reportFileName) {
        if (StringUtils.isBlank(reportFileName)) {
            return null;
        }
        Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}");
        Matcher matcher = pattern.matcher(reportFileName);
        if (matcher.find()) {
            String dateTimeStr = matcher.group();
            return LocalDateTime.parse(dateTimeStr, onlineReportDateTimeFormatter);
        }
        return null;
    }

    public static boolean checkBusCategory(String busCategory) {
        if (StringUtils.isBlank(busCategory)) {
            return false;
        }
        switch (busCategory) {
            case "MFO", "MKK", "MFK" -> {
                return true;
            }
            default -> {
                return false;
            }
        }
    }

    public static String generateResponseReportFileName(String userId, String packageName) {
        return userId.substring(0, 6) + "_" + packageName + "_" + LocalDateTime.now().format(responseReportDateTimeFormatter);
    }

    public static String getMemberCodeFromFileName(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return null;
        }
        String[] parts = fileName.split("_");
        if (parts.length > 1) {
            return parts[0];
        } else {
            return null;
        }
    }

    public static String normalize(String value) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        return value.replaceAll("[^А-Яа-яA-Za-z0-9]", "");
    }

    public static Date localDatetoDate(LocalDate date) {
        if (date == null) {
            return null;
        }
        return Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    public static void createFolder(String folderPath) {
        File folder = new File(folderPath);
        if (!folder.exists()) {
            try {
                Files.createDirectories(Path.of(folderPath));
            } catch (IOException e) {
                log.error("Could not create folder: {}", folderPath, e);
                throw new RuntimeException(e);
            }
        }
    }

    public static void removeFile(String filePath) {
        try {
            Path path = Path.of(filePath);
            if (Files.exists(path)) {
                Files.delete(path);
            }
        } catch (IOException e) {
            log.warn("File {} hasn't been deleted", filePath);
        }
    }
}
