package cc.smtweb.system.bpm.spring.dao;

import cc.smtweb.system.bpm.spring.entity.UploadDataVO;
import cc.smtweb.system.bpm.util.ThumbImage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
public class ImageAttachDao {
    public static final String APPLICATION_OCTET_STREAM = "application/octet-stream";

    public void makeThumb(UploadDataVO data, boolean isThumb, File targetFile, Integer size) throws IOException {
        boolean imageType = false;
        String fileName = data.getName();
        String contentType = data.getContentType();

        if (contentType.startsWith("image/")) {
            imageType = true;
        } else if (contentType.equals(APPLICATION_OCTET_STREAM)) {
            String fileExt = fileName.substring(fileName.lastIndexOf("."));

            if (StringUtils.isNotEmpty(fileExt)) {
                switch (fileExt.toLowerCase()) {
                    case ".jpg":
                    case ".jpeg":
                        contentType = "image/jpg";
                        imageType = true;
                        break;
                    case ".gif":
                        contentType = "image/gif";
                        imageType = true;
                        break;
                    case ".png":
                        contentType = "image/png";
                        imageType = true;
                        break;
                    default:
                        break;
                }

                if (imageType) {
                    data.setContentType(contentType);
                }
            }
        }

        if (imageType) {
            int thumbHeight = 80;
            if (size != null) {
                thumbHeight = (size > 500) ? 500: size;
            }

            ThumbImage thumbImage = new ThumbImage();

            thumbImage.makeThumb(isThumb, targetFile, thumbHeight);
            data.setWidth(thumbImage.getImageWidth());
            data.setHeight(thumbImage.getImageHeight());
        }
    }
}
