#!/usr/bin/env node

'use strict'

require('../lib/prototype');
var http = require('../lib/http-request');
var fs = require('fs')
var path = require('path')
var url = require('url')

var requrl
var saveurl
var cpus
var seconds
var headers = {}

var processArgs = require('../lib/args')
var argMapping = processArgs(process.argv.slice(2))

for (var key in argMapping) {
	let value = argMapping[key];
	switch (key) {
		case "-?":
		case "/?":
		case "-h":
		case "--help":
			console.log(`
--------------------
Node.js多线程下载参数说明
--------------------

-o		输出文件名
-u		下载文件路径
-H		请求头，可多次传入
-c		启动多少个线程，可不传，默认为cpu核数
-s		秒数。超过这个秒数则强行终止，默认为120秒

--------------------
示例
--------------------

dl http://dl.example.com/test.file

或者

dl -o=./test.file -u=http://dl.example.com/test.file -h='content-type:application/json'`);
			process.exit(0);
			break;
		case "-o":
			saveurl = path.resolve(process.cwd(), value);
			break;
		case "-c":
			cpus = parseInt(value)
			break;
		case "-u":
			requrl = value;
			break;
		case "-s":
			seconds = parseInt(value);
			break;
		case "-H":
			var head = value.trim('"', "'").split(':');
			headers[head[0]] = head[1]
			break;
	}
	if (key.startsWith('http')) {
		requrl = key;
	}
}

if (saveurl == undefined) {
	var basename = path.parse(requrl).base;
	saveurl = path.resolve(process.cwd(), basename)
}

if (seconds == undefined) {
	seconds = 120;
}

; (async () => {
	console.time('download')
	var result = await http.DownloadParallel({
		requrl,
		saveurl,
		cpus,
		seconds,
		headers,
		log: true,
	});
	// var result = await http.Download(requrl, saveas, maxlen);
	console.timeEnd('download')
	console.log(result)
	if (result.receive == result.maxLength) {
		console.log(`文件保存到： ${saveurl}`)
	}
})();


