package com.ruoyi.common.utils.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.StringUtils;

public final class PathUtils
{
    public static String replaceExtension(String src, String newExt)
    {
        if(StringUtils.isEmpty(src))
            return "";

        String suffix = FileUtil.getSuffix(src);
        StringBuilder dst = new StringBuilder();
        if(StringUtils.isNotEmpty(suffix))
            dst.append(src, 0, src.length() - suffix.length());
        else
            dst.append(src);
        if(dst.lastIndexOf(".") == dst.length() - 1)
            dst.deleteCharAt(dst.length() - 1);
        if(newExt.startsWith("."))
            dst.append(newExt);
        else
            dst.append(".").append(newExt);
        return dst.toString();
    }

    public static String removeExtension(String src)
    {
        if(StringUtils.isEmpty(src))
            return "";

        String suffix = FileUtil.getSuffix(src);
        StringBuilder dst = new StringBuilder();
        if(StringUtils.isNotEmpty(suffix))
            dst.append(src, 0, src.length() - suffix.length());
        else
            dst.append(src);
        if(dst.lastIndexOf(".") == dst.length() - 1)
            dst.deleteCharAt(dst.length() - 1);
        return dst.toString();
    }

    public static String appendPaths(String...parts)
    {
        String res = "";
        for(String part : parts)
        {
            if(StringUtils.isEmpty(part))
                continue;
            part = normalizeSlash(part);
            if(res.isEmpty())
            {
                res = part;
            }
            else
            {
                part = removeStartSlash(part);
                res = removeEndSlash(res) + "/" + part;
            }
        }
        return res;
    }

    public static String normalizeSlash(String part)
    {
        if(StringUtils.isEmpty(part))
            return "";
        return part.replaceAll("\\\\", "/");
    }

    public static String removeStartSlash(String part)
    {
        if(StringUtils.isEmpty(part))
            return "";
        int i = 0;
        while(part.charAt(i++) == '/');
        if(i == 0)
            return part;
        else if(i >= part.length())
            return "";
        else
            return part.substring(i - 1);
    }

    public static String removeEndSlash(String part)
    {
        if(StringUtils.isEmpty(part))
            return "";
        int i = part.length();
        while(part.charAt(--i) == '/');
        if(i <= 0)
            return "";
        else if(i == part.length() - 1)
            return part;
        else
            return part.substring(0, i);
    }

    private PathUtils() {}
}
