package com.pine.admin.modules.youpaiyun.util;

import com.UpYun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;

/**
 * Created by dujinkai on 17/5/8.
 * 又拍云上传工具
 */
public class YunUploadUtils {

    /**
     * 调试工具
     */
    private Logger logger = LoggerFactory.getLogger(YunUploadUtils.class);

    private static final YunUploadUtils INSTANCE = new YunUploadUtils();

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

    private YunUploadUtils() {
    }

    public static YunUploadUtils getInstance() {
        return INSTANCE;
    }


    /**
     * 上传又拍云
     *
     * @param upYunConf   又拍云设置
     * @param inputStream 输入流
     * @param bytes       图片字节
     * @return 返回图片在又拍云的地址
     */
    public String uploadToUpYun(InputStream inputStream, byte[] bytes) {
        logger.debug("Being to uploadToUpYun.....");
        if (bytes == null || bytes.length == 0) {
            logger.error("uploadToUpYun fail due to bytes is empty ....");
            return "";
        }

        // 如果上传的不是图片 则直接返回
        if (!isPicture(bytes)) {
            throw new RuntimeException("file is not a picture ...");
        }
        try {
            String picName = String.valueOf(System.currentTimeMillis()) + ".jpg";
            String date = simpleDateFormat.format(Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00")).getTime());
            String filePath = "/" + date + "/" + picName;
            UpYun upYun = new UpYun(UpYunConf.nameSpace.trim(), UpYunConf.userName.trim(), UpYunConf.password.trim());
            upYun.setDebug(true);
            upYun.setContentMD5(MD5Utils.getInstance().createMd5ForImageUpload(inputStream));
            upYun.setFileSecret("");
            // 上传文件
            if (upYun.writeFile(filePath, bytes, true)) {
                return UpYunConf.address + date + "/" + picName;
            }
        } catch (Exception e) {
            logger.error("uploadToUpYun fail ....", e);
        }
        return "";
    }

    /**
     * 判断是否是图片
     *
     * @param bytes 字节数组
     * @return 是图片返回true  否则返回false
     */
    private boolean isPicture(byte[] bytes) {
        try {
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
            return image != null;
        } catch (IOException e) {
            logger.error("file is not a picture ...", e);
            return false;
        }
    }
}
