
const co = require('co');
const OSS = require('ali-oss');

const config = require("../project.json");
const chalk = require('chalk');

//只打包js时，自执行上传
uploadSingleJs();

function uploadSingleJs(url) {

    if (!url) {//不传的时候

        if (!config.type) {
            throw new Error(`project.json 的type不存在.`)
        }

        if (!config.name) {
            throw new Error(`project.json 的name不存在.`)
        }

        const now = new Date();
        const version = Math.round(now.getTime() / 1000);

        url = `${config.type}/${config.name}/${version}`;

        require("./createHtml")(`${config.type}/${config.name}/${version}`);

	    console.log(chalk.bgGreen(`版本号：\n${version}`));

    }

	const client = new OSS({
		region: 'oss-cn-hangzhou',
		accessKeyId: "LTAI5tPUSSxgkEmKPAfVXUQQ",
		accessKeySecret: "6sk3EDd1BYrXlAUoh8maMuN7hOMkh1",
		bucket: 'duiba'
	});

	//单js文件上传
    co(function* () {
        const originPath = `/db_games/${url}/output.js`;
	    let originFile;
	    try {
            originFile = yield client.head(originPath);
        } catch (error) {
            originFile = error;
        }
        if (originFile.status === 404)
            yield client.put(originPath, "./released/output.js");
    });

	//js.map
	co(function* () {
		const originPath = `/db_games/${url}/map_123_map/output.js.map`;
		var originFile;
		try {
			originFile = yield client.head(originPath);
		} catch (error) {
			originFile = error;
		}
		if (originFile.status === 404)
			yield client.put(originPath, "./released/output.js.map");
	});
}

module.exports = uploadSingleJs
