import Exif from 'exif-js'
import { compressProcess } from './compressor'
import { isSupportHtml5Plus } from '@/utils/platform'

export function compress ({file, dst, compressSize, quality = 20}) {

    if(isSupportHtml5Plus) {
        return plusCompress(file, dst, compressSize, quality)
    } else {
        return webCompress(file, compressSize)
    }
    
}

export function webCompress(file, compressSize = 100) {
    let Orientation;
    //去获取拍照时的信息，解决拍出来的照片旋转问题
    Exif.getData(file, function(){
        Orientation = Exif.getTag(this, 'Orientation');
    });

    if (/^image/.test(file.file.type)) {
        let result = file.content;
        let img = new Image();
        img.src = result;
        //判断图片是否大于1M,是就直接上传，反之压缩图片
        // if (result.length <= (100 * 1024)) {
        if (result.length <= (compressSize * 1024)) {
            return Promise.resolve(file.file)
        }else {
            return new Promise((resolve, reject) => {
                compressProcess([file.file], function(files) {
                    return resolve(new window.File(files, file.file.name, {type: file.file.type}))
                })
            })
        }
    } else {
        console.error("文件类型错误。")
        return Promise.reject()
    }
}
export function plusCompress(src, dst, compressSize, quality) {

    return new Promise((resolve, reject) => {

        function compressImage() {
            window.plus.zip.compressImage({
                src,
                dst,
                overwrite: true,
                quality: quality
            },
            function(event) {
                resolve(event.target)
            },
            function(error) {
                console.log(error)
                reject(error)
            })
        }

        if(compressSize) {
            plus.io.resolveLocalFileSystemURL(src, function (entry) {
                entry.getMetadata(function (metaData) {
                   if(metaData.size <= compressSize) {
                        resolve(src)
                   } else {
                        compressImage()
                   }
                }, function () {
                    console.error("getMetadata fail")
                })
            }, function () {
                console.error('resolveLocalFileSystemURL fail')
            })
        } else {
            compressImage()
        }
    })
}