package com.op.file.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.bson.types.ObjectId;
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.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.model.GridFSFile;

@Primary
@Service
public class MongoFileImpl implements ISysFileService {

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

	/**
	 * 域名或本机访问地址
	 */
	@Value("${mongo.domain}")
	public String domain;
	@Autowired
	private GridFsTemplate gridFsTemplate;
	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public InputStream searchGridFs(String id) {
		InputStream inputStream = null;
		try {
			Query query = Query.query(Criteria.where("_id").is(id));
			GridFSFile gridFSDBFile = gridFsTemplate.findOne(query);
			GridFsResource gridFsResource = new GridFsResource(gridFSDBFile,
					defaultGridFsBucket().openDownloadStream(gridFSDBFile.getObjectId()));
			inputStream = gridFsResource.getInputStream();
		} catch (Exception e) {
			log.error("Mongo searchGridFs error", e);
		} finally {
		}
		return inputStream;
	}

	private GridFSBucket defaultGridFsBucket() {
		// 通过mongoTemplate来获取默认的数据库连接
		MongoDatabaseFactory mongoDatabaseFactory = mongoTemplate.getMongoDatabaseFactory();
		MongoDatabase db = mongoDatabaseFactory.getMongoDatabase("op_cloud");
		// 创建GridFSBucket 并指定文件系统使用的bucket
		return GridFSBuckets.create(db);
	}

	// 转byte[]
	public static byte[] toByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
		}
		return output.toByteArray();
	}

	@Autowired
	private MongoService mongoService;

	/**
	 * 图片上传
	 *
	 * @param file
	 * @param
	 * @return
	 * @throws Exception
	 */
	@Override
	public String uploadFile(MultipartFile file) throws Exception {
		String fileName = file.getOriginalFilename();
		String id = this.mongoService.uploadFile(file, fileName);
		String url = domain + "/downLoadFile?id=" + id+"&fileName="+fileName;
		return url;
	}

	/**
	 * 图片预览
	 *
	 * @param
	 * @return
	 */
	@Override
	public byte[] imageOnline(String id) {
		return this.mongoService.downloadImageByte(id);
	}

}
