package io.renren.common.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Random;

@Component
public class LocalFile {


    public static String baseDirtory;

    @Value("${file.baseDirtory}")
    public void setBaseDirtory(String baseDirtory) {
        LocalFile.baseDirtory = baseDirtory;
    }


    public static String saveDefault(byte[] bytes, String fileName, String ditcory) throws IOException {
        System.out.println(baseDirtory);
        if (ditcory == null) {
            ditcory = new Random().nextInt(99999999) + "/";
        }
        String saveDic = MessageFormat.format("{0}{1}", baseDirtory, ditcory);
        File dic = new File(saveDic);
        FileUtils.forceMkdir(dic);
//		String format = DrayFileUtils.getFileTypeByStream(bytes);
        String format = StringUtils.substringAfterLast(fileName, ".");
        String name = StringUtils.substringBeforeLast(fileName, ".");
        if (format.equals("jpeg")) {
            format = "jpg";
        }
        if (StringUtils.isBlank(format)) {
            format = "jpg";
        }
        String filePath = MessageFormat.format("{0}{1}.{2}", saveDic, name, format);
        File file = new File(filePath);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fout = new FileOutputStream(file);
        IOUtils.write(bytes, fout);
        fout.flush();
        fout.close();

        return MessageFormat.format("{0}{1}.{2}", ditcory, name, format);
    }


}
