package com.example.baidu.ueditor.upload;

import com.example.SpringContextUtils;
import com.example.baidu.ueditor.define.AppInfo;
import com.example.baidu.ueditor.define.BaseState;
import com.example.baidu.ueditor.define.State;

import java.io.*;

import com.example.util.AliyunOSSUtil;
import com.example.util.uploadLocalost.FileLocalUtils;
import com.example.util.uploadLocalost.UploadResultDto;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StorageManager {
    private static final Logger logger = LoggerFactory.getLogger(StorageManager.class);
    public static final int BUFFER_SIZE = 8192;

    public StorageManager() {
    }

    public static State saveBinaryFile(byte[] data, String path) {
        File file = new File(path);

        State state = valid(file);

        if (!state.isSuccess()) {
            return state;
        }

        try {
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(file));
            bos.write(data);
            bos.flush();
            bos.close();
        } catch (IOException ioe) {
            return new BaseState(false, AppInfo.IO_ERROR);
        }

        state = new BaseState(true, file.getAbsolutePath());
        state.putInfo("size", data.length);
        state.putInfo("title", file.getName());
        return state;
    }

    public static State saveFileByInputStream(InputStream is, String path,
                                              long maxSize) {
        State state = null;

        File tmpFile = getTmpFile();

        byte[] dataBuf = new byte[2048];
        BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
            int count = 0;
            while ((count = bis.read(dataBuf)) != -1) {
                bos.write(dataBuf, 0, count);
            }
            bos.flush();
            bos.close();

            if (tmpFile.length() > maxSize) {
                tmpFile.delete();
                return new BaseState(false, AppInfo.MAX_SIZE);
            }
            state = saveTmpFile(tmpFile, path);
            if (state.isSuccess()) {
                tmpFile.delete();
            }
            return state;
        } catch (IOException e) {
        }
        return new BaseState(false, AppInfo.IO_ERROR);
    }

    public static State saveFileByInputStream(InputStream is, String path) {
        State state = null;
        File tmpFile = getTmpFile();
        byte[] dataBuf = new byte[2048];
        BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
            int count = 0;
            while ((count = bis.read(dataBuf)) != -1) {
                bos.write(dataBuf, 0, count);
            }
            bos.flush();
            bos.close();
            state = saveTmpFile(tmpFile, path);
            if (!state.isSuccess()) {
                tmpFile.delete();
            }
            return state;
        } catch (IOException e) {
        }
        return new BaseState(false, AppInfo.IO_ERROR);
    }

    private static File getTmpFile() {
        File tmpDir = FileUtils.getTempDirectory();
        String tmpFileName = (Math.random() * 10000 + "").replace(".", "");
        return new File(tmpDir, tmpFileName);
    }

    /**
     * oss图片存储
     */
//    private static State saveTmpFile(File tmpFile, String path) {
//        State state;
//        AliyunOSSUtil aliyunOSSUtil= (com.example.util.AliyunOSSUtil) SpringContextUtils.getBean("aliyunOSSUtil");
//        String upolad = aliyunOSSUtil.upolad(tmpFile, path);
//        state = new BaseState(true);
//        state.putInfo("size", tmpFile.length());
//        state.putInfo("url", upolad);
//        return state;
//    }

    /**
     * 本地图片存储
     */
    private static State saveTmpFile(File tmpFile, String path) {
        State state;
        String extension = path.split("\\.")[1];
        FileLocalUtils fileLocalUtils = (FileLocalUtils) SpringContextUtils.getBean("fileLocalUtils");
        UploadResultDto uploadResultDto = fileLocalUtils.uploadFile(fileToByteArray(tmpFile), "."+extension);
        state = new BaseState(true);
        state.putInfo("size", tmpFile.length());
        state.putInfo("url", uploadResultDto.getServerUrl());
        state.putInfo("httpurl", uploadResultDto.getUrl());
        return state;
    }

    private static State valid(File file) {
        File parentPath = file.getParentFile();

        if ((!parentPath.exists()) && (!parentPath.mkdirs())) {
            return new BaseState(false, AppInfo.FAILED_CREATE_FILE);
        }

        if (!parentPath.canWrite()) {
            return new BaseState(false, AppInfo.PERMISSION_DENIED);
        }

        return new BaseState(true);
    }

    /**
     * 文件到字节数组
     *
     * @param file 文件
     * @return 字节数组
     */
    private static byte[] fileToByteArray(File file) {
        try {
            byte[] bArray = new byte[(int) file.length()];
            FileInputStream fis = new FileInputStream(file);
            fis.read(bArray);
            fis.close();
            file.delete();
            return bArray;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("文件到字节数组,异常", e);
        }
        return null;
    }
}
