package com.aip.gateway.api.aip.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;

@Slf4j
public class AipFileUtils {

    public static long getSize(String fileName) {
        File file = new File(fileName);
        return file.length();
    }

    public static boolean isExists(String fileName) {
        File file = new File(fileName);
        return file.exists();
    }

    public static String getFileName(String fileName) {
        String name = FilenameUtils.getName(fileName);
        return name;
    }
    public static String getFileNameWithoutExtension(String fileName) {
        return StringUtils.stripFilenameExtension(getFileName(fileName));
    }
    public static String getExtension(String fileName) {
        String fileExt = StringUtils.getFilenameExtension(fileName);
        if (fileExt == null) {
            return ".";
        }
        return "." + fileExt.toLowerCase();
    }

    public static boolean delete(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }

    public static boolean streamToFile(byte[] byteArrayData, String fileName) {
        boolean result = true;
        try {
            FileUtils.writeByteArrayToFile(new File(fileName), byteArrayData);
        }
        catch (IOException e) {
            log.error("streamToFile: IOException: {}, {}", fileName, e.getMessage());
            result = false;
        }
        return result;
    }

}
