package com.liquidnet.service.adam.service.sys;

import com.liquidnet.service.adam.incrementer.CustomIdGenerator;
import com.liquidnet.service.adam.service.sys.IAdamSysMongoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.entity.ContentType;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsCriteria;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import static org.springframework.data.mongodb.core.query.Query.query;

/**
 * MongoDB服务
 *
 * @author lichen
 */
@Slf4j
@Service
public class AdamSysMongoServiceImpl implements IAdamSysMongoService {

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Autowired
    private CustomIdGenerator customIdGenerator;

    @Override
    public String uploadFile(byte[] bytes, String fileName) {
        String ex = null;
        try {
            InputStream inputStream = new ByteArrayInputStream(bytes);
            Long aLong = customIdGenerator.nextId(inputStream);
            ex = String.valueOf(aLong).concat(fileName.substring(fileName.lastIndexOf(".")));
            ObjectId objectId = gridFsTemplate.store(inputStream, ex, ContentType.APPLICATION_OCTET_STREAM.toString());
            log.debug("MongoDB上传文件".concat(Thread.currentThread().getStackTrace()[1].getMethodName()).concat(" - { ObjectId:").concat(objectId.toString()).concat(" }"));

        } catch (Exception e) {
            log.error("MongoDB存储异常", e);
            return null;
        }
        return ex;
    }

    @Override
    public boolean deleteFile(String filename) {
        try {
            gridFsTemplate.delete(creat(filename));
        } catch (Exception e) {
            log.error("MongoDB删除异常", e);
            return false;

        }

        return true;
    }

    @Override
    public byte[] downFile(String filename) {
        byte[] result = null;
        GridFsResource resource = gridFsTemplate.getResource(filename);
        try (InputStream is = resource.getInputStream()) {
            result = IOUtils.toByteArray(is);
        } catch (Exception e) {
            log.error("MongoDB查询异常", e);
            return null;
        }

        return result;
    }

    private Query creat(String filename) {
        return query(GridFsCriteria.whereFilename().is(filename));
    }

}