package cn.com.qmth.stmms.biz.file.store.impl;

import cn.com.qmth.stmms.biz.file.store.FileStore;
import com.aliyun.oss.common.utils.BinaryUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 本地磁盘文件管理工具
 */
public class DiskStore implements FileStore {

    private static final Logger log = LoggerFactory.getLogger(DiskStore.class);

    private File rootDir;

    public DiskStore(String path) {
        rootDir = new File(path);
        if (!rootDir.exists() && !rootDir.mkdirs()) {
            //自动创建目录失败
            throw new IllegalArgumentException("[file.store]" + path + ": auto mkdir faile");
        } else if (rootDir.isFile()) {
            //判断是否不是目录
            throw new IllegalArgumentException("[file.store]" + path + ": is a file");
        }
    }

    @Override
    public void write(String path, InputStream ins, String md5) throws Exception {
        byte[] data = IOUtils.toByteArray(ins);
        if (!BinaryUtil.encodeMD5(data).equalsIgnoreCase(md5)) {
            throw new RuntimeException("md5 validate faile");
        }
        File target = new File(rootDir, path);
        target.getParentFile().mkdirs();
        FileOutputStream ous = new FileOutputStream(target);
        ous.write(data);
        IOUtils.closeQuietly(ous);
    }

    @Override
    public byte[] read(String path) throws Exception {
        File file = new File(rootDir, path);
        if (file.exists() && file.isFile()) {
            FileInputStream ins = new FileInputStream(file);
            FileChannel channel = ins.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
                //
            }
            IOUtils.closeQuietly(ins);
            IOUtils.closeQuietly(channel);
            return byteBuffer.array();
        } else {
            throw new RuntimeException("read file unexist:" + path);
        }
    }

    @Override
    public boolean exist(String path) {
        File file = new File(rootDir, path);
        return file.exists() && file.isFile();
    }

    @Override
    public void close() {
    }

}
