package com.mineplex.studio.region;

import it.unimi.dsi.fastutil.ints.IntIntPair;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegionFileUtil {
    private static final Pattern REGION_FILE_PATTERN;

    static {
        final StringJoiner extensionJoiner = new StringJoiner("|");

        // Add default file extensions
        extensionJoiner.add(Pattern.quote(".mca"));

        REGION_FILE_PATTERN = Pattern.compile("^r\\.(-?\\d+)\\.(-?\\d+)(" + extensionJoiner + ")$");
    }

    private RegionFileUtil() {}

    public static File[] getAllRegionFiles(final File folder) {
        return folder.listFiles((final File dir, final String name) ->
                REGION_FILE_PATTERN.matcher(name).matches());
    }

    public static List<IntIntPair> getAllRegionFilesCoords(final File folder) {
        final File[] files = folder.listFiles();
        if (files == null) {
            return Collections.emptyList();
        }

        final List<IntIntPair> chunkPosList = new ArrayList<>(files.length);
        for (final File file : files) {
            final Matcher regionFileMatcher = REGION_FILE_PATTERN.matcher(file.getName());
            if (regionFileMatcher.find()) {
                final int xPos = Integer.parseInt(regionFileMatcher.group(1));
                final int zPos = Integer.parseInt(regionFileMatcher.group(2));
                chunkPosList.add(IntIntPair.of(xPos, zPos));
            }
        }

        return chunkPosList;
    }
}
