const OSS = require('ali-oss')
const co = require('co')
const crypto = require('crypto')
const fs = require('fs')
const config = require('config')

const client = new OSS({
    bucket: '51query',
    accessKeyId: 'LTAI6Glaum6TDzKf',
    accessKeySecret: 'zmNjWhmOD1nIClZ3hoDmGrdNNiBJBi',
    secure: true,
    region: "oss-cn-hangzhou"
})


function upload_image(key, data) {
    return co(function*() {
        // use 'chunked encoding'
        //var stream = fs.createReadStream('./exp.js');
        data = data.replace(/^data:image\/\S+?;base64,/,"");
        var result = yield client.put(key, new Buffer(data, 'base64'));
        return result
    }).catch(function (err) {
        console.log('upload_image error: ', err);
    });
}

function upload(key, data) {
    return co(function*() {
        // use 'chunked encoding'
        //var stream = fs.createReadStream('./exp.js');
        var result = yield client.put(key, new Buffer(data));
        return result
    }).catch(function (err) {
        console.log('upload error: ', err);
    });
}

const getUploadSign = (dirPath, fileName) => {
    const {AccessKeyId, Host, AccessKeySecret} = config.oss
    let callback = {
        "callbackUrl": `${config.host}/kqyx/oss/callback`,
        "callbackBody": "filename=${object}&size=${size}&mimeType=${mimeType}",
        "callbackBodyType": "application/x-www-form-urlencoded"
    }
    callback = JSON.stringify(callback)
    const callbackbody = new Buffer(callback).toString('base64')
    const end = new Date().getTime() + 300000
    const expiration = new Date(end).toISOString()
    let policyString = {
        expiration,
        conditions: [
            // 1024*1024  1mb限制
            ['content-length-range', 0, 1048576],
            ['starts-with', '$key', 'kqyx']
        ]
    }
    policyString = JSON.stringify(policyString)
    const policy = new Buffer(policyString).toString('base64')
    const signature = crypto.createHmac('sha1', AccessKeySecret).update(policy).digest('base64')

    return {
        AccessKeyId,
        host: Host,
        policy,
        signature,
        fileName,
        dirPath,
        callbackbody
    }
}

const signed_url = (name) => {
    return client.signatureUrl(name)
}


const deleteFile = (key) => {
    co(function*() {
        return yield client.delete(key)
    }).catch(function (err) {
        console.log(err)
        throw err
    })
}

module.exports = {
    upload_image,
    signed_url,
    deleteFile,
    upload
}