package com.ecep.contract.util;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtils {
    public final static String PDF = ".pdf";
    public final static String DOC = ".doc";
    public final static String DOCX = ".docx";
    public final static String XLS = ".xls";
    public final static String XLSX = ".xlsx";
    public final static String PNG = ".png";
    public final static String JPG = ".jpg";
    public final static String JPEG = ".jpeg";
    public final static String JSON = ".json";
    public final static String FILE_DB_THUMBS = "Thumbs.db";
    public final static String FILE_DB_JSON = "db.json";
    public final static String FILE_BLACK_LIST_JSON = "black_list.json";
    public final static String FILE_B1001_JSON = "b1001.json";

    /**
     * 检查文件是否符合后缀要求
     *
     * @param name           文件名
     * @param fileExtensions 后缀
     */
    public static boolean withExtensions(String name, String... fileExtensions) {
        for (String fn : fileExtensions) {
            if (name.endsWith(fn)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 返回 district 中关于省份的部门zi
     *
     * @param district 地区
     * @return 省份名称
     */
    public static String getParentPrefixByDistrict(String district) {
        int indexOf = district.indexOf("省");
        if (indexOf != -1) {
            return district.substring(0, indexOf);
        }

        indexOf = district.indexOf("自治区");
        if (indexOf != -1) {
            return district.substring(0, 2);
        }

        indexOf = district.indexOf("市");
        if (indexOf != -1) {
            return district.substring(0, indexOf);
        }
        return null;
    }

    public static String escapeFileName(String fileName) {
        String patternStr = "[\\\\/:*?\"<>|]";
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(fileName);
        return matcher.replaceAll("_");
    }

    public static boolean isHiddenFile(File file) {
        String fileName = file.getName();
        if (fileName.equals(FILE_DB_THUMBS)) {
            return true;
        }
        return fileName.startsWith("~$");
    }
}
