const http = require("http")
const https = require("https")
const urlData = require('url');
var zlib = require('zlib');
exports.httpsSend = (url, RetFun, method_ = "GET", POSTDATA = "", headers_ = {}, followAllRedirects_ = true, timeout_ = 5000) => {
	let codeType = undefined;
	let url_ = ""
	if (url["协议"] != undefined) {
		url["protocol"] = url["协议"]
	}
	if (url["主机域名"] != undefined) {
		url["host"] = url["主机域名"]
	}
	if (url["端口"] != undefined) {
		url["port"] = url["端口"]
	}
	if (url["路径"] != undefined) {
		url["path"] = url["路径"]
	}
	if (url["编码"] != undefined) {
		codeType = url["编码"]
	}
	if (url["protocol"] != undefined) {
		var options = {
			hostname: url["host"],
			method: method_,
			headers: headers_,
			followAllRedirects: followAllRedirects_,
			timeout: timeout_,
			path: url["path"]
		}
		if (url["GZIP"] != undefined) {
			if (url["GZIP"] == true) {
				options["GZIP"] = true;
			}
		}
		if (url["字节流"] != undefined) {
			if (url["字节流"] == true) {
				options["字节流"] = true;
			}
		}
		if (url["port"] != 80) {
			options["hostname"] = options["hostname"] + ":" + url["port"]
		}
		if (url["port"] == undefined) {
			url["port"] = 80
		}
	} else {
		if (url["链接地址"] != undefined) {
			if (url["链接地址"]) {
				url_ = url["链接地址"]
				url = UrlSet(url["链接地址"])
			}
			if (url["url"]) {
				url_ = url["url"]
				url = UrlSet(url["url"])
			}
		} else {
			url_ = url
			url = UrlSet(url)
		}
		let Path_ = PathSet(url_)
		var options = {
			hostname: url,
			method: method_,
			headers: headers_,
			followAllRedirects: followAllRedirects_,
			timeout: timeout_,
			path: Path_
		}
		if (url["GZIP"] != undefined) {
			if (url["GZIP"] == true) {
				options["GZIP"] = true;
			}
		}
		if (url["字节流"] != undefined) {
			if (url["字节流"] == true) {
				options["字节流"] = true;
			}
		}
	}
	let IntUrl = []
	if (url["重定向"] != undefined) {
		options["重定向"] = url["重定向"]
	}
	httpsSendYes(options, POSTDATA, (endObj) => {
		if (RetFun != undefined) {
			RetFun(endObj)
		}
	}, IntUrl, codeType)
}
exports.httpSend = (url, RetFun, method_ = "GET", POSTDATA = "", headers_ = {}, followAllRedirects_ = true, timeout_ = 5000) => {
	let url_ = ""
	let codeType = undefined
	if (url["协议"] != undefined) {
		url["protocol"] = url["协议"]
	}
	if (url["主机域名"] != undefined) {
		url["host"] = url["主机域名"]
	}
	if (url["端口"] != undefined) {
		url["port"] = url["端口"]
	}
	if (url["路径"] != undefined) {
		url["path"] = url["路径"]
	}
	if (url["编码"] != undefined) {
		codeType = url["编码"]
	}
	if (url["protocol"] != undefined) {
		var options = {
			hostname: url["host"],
			method: method_,
			headers: headers_,
			followAllRedirects: followAllRedirects_,
			timeout: timeout_,
			path: url["path"]
		}
		if (url["GZIP"] != undefined) {
			if (url["GZIP"] == true) {
				options["GZIP"] = true;
			}
		}
		if (url["字节流"] != undefined) {
			if (url["字节流"] == true) {
				options["字节流"] = true;
			}
		}
		if (url["port"] == undefined) {
			url["port"] = 80
		}
		if (url["port"] != 80) {
			options["hostname"] = options["hostname"] + ":" + url["port"]
		}
		if (url["编码"] != undefined) {
			codeType = url["编码"]
		}
	} else {
		if (url["链接地址"]) {
			if (url["链接地址"]) {
				url_ = url["链接地址"]
				url = UrlSet(url["链接地址"])
			}
			if (url["url"]) {
				url_ = url["url"]
				url = UrlSet(url["url"])
			}
		} else {
			url_ = url
			url = UrlSet(url)
		}
		let Path_ = PathSet(url_)
		var options = {
			hostname: url,
			method: method_,
			headers: headers_,
			followAllRedirects: followAllRedirects_,
			timeout: timeout_,
			path: Path_
		}
		if (url["GZIP"] != undefined) {
			if (url["GZIP"] == true) {
				options["GZIP"] = true;
			}
		}
		if (url["字节流"] != undefined) {
			if (url["字节流"] == true) {
				options["字节流"] = true;
			}
		}
	}
	let IntUrl = []
	if (url["重定向"] != undefined) {
		options["重定向"] = url["重定向"]
	}
	httpSendYes(options, POSTDATA, (endObj) => {
		if (RetFun != undefined) {
			RetFun(endObj)
		}
	}, IntUrl, codeType)
}
function httpsSendYes(options, POSTDATA, RetFun, IntUrl = [], codeType) {
	//使用http 发送
	var req = https.request(options, function (res) {
		//设置字符编码
		if (codeType != undefined) {
			res.setEncoding(codeType);
		}
		//返回数据流
		var _data = "";
		var _data_ = []
		//数据
		res.on('data', function (chunk) {
			if (options["GZIP"] != undefined || options["字节流"] != undefined) {
				if (options["GZIP"] == true || options["字节流"] == true) {
					_data_.push(chunk);
				}
			}
			if (options["字节流"] == undefined) {
				_data += chunk;
			} else {
				if (options["字节流"] == false) {
					_data += chunk;
				}
			}
		});
		// 结束回调
		res.on('end', function () {
			if (options["重定向"] == undefined || options["重定向"] == true) {
				if (res.statusCode == 301 || res.statusCode == 302) {
					if (res.headers["location"]) {
						if (IntUrl.indexOf(res.headers["location"]) == -1) {
							IntUrl[IntUrl.length] = res.headers["location"]
							let location = locationSet(res.headers["location"], options, true)
							options["hostname"] = UrlSet(location)
							options["path"] = PathSet(res.headers["location"])
							if (location.substring(0, 8).indexOf("https://") != -1) {
								httpsSendYes(options, POSTDATA, RetFun, IntUrl, codeType)
							} else {
								httpSendYes(options, POSTDATA, RetFun, IntUrl, codeType)
							}
							return
						}
					}
				}
			}
			if (options["GZIP"]) {
				if (options["GZIP"] == true) {
					var buffer = Buffer.concat(_data_);
					let endObj = {
						"返回协议头": res.headers,
						"返回状态码": res.statusCode,
						"整体状态": res
					}
					zlib.gunzip(buffer, function (err, decoded) {
						endObj["数据"] = decoded.toString()
						if (RetFun != undefined) {
							RetFun(endObj)
						}
					})
					return;
				}
			}
			let endObj = {
				"数据": _data,
				"返回协议头": res.headers,
				"返回状态码": res.statusCode,
				"整体状态": res
			}
			if (options["字节流"] != undefined) {
				if (options["字节流"] == true) {
					endObj["数据"] = _data_;
				}
			}
			if (RetFun != undefined) {
				RetFun(endObj)
			}
		});
		//错误回调 
		//这个必须有,不然会有不少"麻烦"
		req.on('error', function (e) {
			//console.log('网络请求错误:' + e.message);
			let endObj = {
				"数据": "",
				"返回协议头": "失败，无协议头",
				"返回状态码": 0,
				"原因": e.message
			}
			if (RetFun != undefined) {
				RetFun(endObj)
			}
		});
	});
	req.write(POSTDATA);
	req.end();
}
function httpSendYes(options, POSTDATA, RetFun, IntUrl = [], codeType) {
	//使用http 发送
	let options_ = optionsIP(options);
	var req = http.request(options_, function (res) {
		//设置字符编码
		if (codeType != undefined) {
			res.setEncoding(codeType);
		}
		//返回数据流
		var _data = "";
		var _data_ = [];
		//数据
		res.on('data', function (chunk) {
			if (options["GZIP"] != undefined || options["字节流"] != undefined) {
				if (options["GZIP"] == true || options["字节流"] == true) {
					_data_.push(chunk);
				}
			}
			if (options["字节流"] == undefined) {
				_data += chunk;
			} else {
				if (options["字节流"] == false) {
					_data += chunk;
				}
			}
		});
		// 结束回调
		res.on('end', function () {
			if (options["重定向"] == undefined || options["重定向"] == true) {
				if (res.statusCode == 301 || res.statusCode == 302) {
					if (res.headers["location"]) {
						if (IntUrl.indexOf(res.headers["location"]) == -1) {
							IntUrl[IntUrl.length] = res.headers["location"]
							let location = locationSet(res.headers["location"], options_, false)
							options["hostname"] = UrlSet(location)
							options["path"] = PathSet(res.headers["location"])
							if (location.substring(0, 8).indexOf("https://") != -1) {
								httpsSendYes(options, POSTDATA, RetFun, IntUrl, codeType)
							} else {
								httpSendYes(options, POSTDATA, RetFun, IntUrl, codeType)
							}
							return
						}
					}
				}
			}
			if (options["GZIP"]) {
				if (options["GZIP"] == true) {
					var buffer = Buffer.concat(_data_);
					let endObj = {
						"返回协议头": res.headers,
						"返回状态码": res.statusCode,
						"整体状态": res
					}
					zlib.gunzip(buffer, function (err, decoded) {
						endObj["数据"] = decoded.toString()
						if (RetFun != undefined) {
							RetFun(endObj)
						}
					})
					return;
				}
			}
			let endObj = {
				"数据": _data,
				"返回协议头": res.headers,
				"返回状态码": res.statusCode,
				"整体状态": res
			}
			if (options["字节流"] != undefined) {
				if (options["字节流"] == true) {
					endObj["数据"] = _data_;
				}
			}
			if (RetFun != undefined) {
				RetFun(endObj)
			}
		});
		//错误回调 
		//这个必须有,不然会有不少"麻烦"
		req.on('error', function (e) {
			//console.log('网络请求错误:' + e.message);
			let endObj = {
				"数据": "",
				"返回协议头": "失败，无协议头",
				"返回状态码": 0,
				"原因": e.message
			}
			if (RetFun != undefined) {
				RetFun(endObj)
			}
		});
	});
	req.write(POSTDATA);
	req.end();
}
function UrlSet(url) {
	if (url.length >= 7) {
		if (url.substring(0, "http://".length) == "http://") {
			url = url.replace("http://", "")
		}
	}
	if (url.length >= 8) {
		if (url.substring(0, "https://".length) == "https://") {
			url = url.replace("https://", "")
		}
	}
	let path_ = "";
	if (url.indexOf("/") != -1) {
		let pathAll = url.split("/");
		if (pathAll.length >= 1) {
			let hostUrl = pathAll[0];
			path_ = url.replace(hostUrl, "");
			url = url.replace(path_, "")
		}
	}
	return url;
}
function PathSet(url) {
	if (url.length >= 7) {
		if (url.substring(0, "http://".length) == "http://") {
			url = url.replace("http://", "")
		}
	}
	if (url.length >= 8) {
		if (url.substring(0, "https://".length) == "https://") {
			url = url.replace("https://", "")
		}
	}
	let path_ = "";
	if (url.indexOf("/") != -1) {
		let pathAll = url.split("/");
		if (pathAll.length >= 1) {
			let hostUrl = pathAll[0];
			path_ = url.replace(hostUrl, "");
			url = url.replace(path_, "")
		}
	}
	return path_;
}
function optionsIP(options_) {
	let Url_ = urlData.parse("http://" + options_["hostname"] + options_["path"])
	var options = {
		method: options_["method"],
		headers: options_["headers"],
		followAllRedirects: options_["followAllRedirects"],
		timeout: options_["timeout"]
	}
	options["protocol"] = "http:"
	if (Url_["hostname"] == undefined || Url_["hostname"] == null) {
		options["host"] = "0.0.0.0"
	} else {
		options["host"] = Url_["hostname"]
	}
	if (Url_["port"] == undefined || Url_["port"] == null) {
		options["port"] = 80
	} else {
		options["port"] = parseInt(Url_["port"])
	}
	if (Url_["path"] == undefined || Url_["path"] == null) {
		options["path"] = "/"
	} else {
		options["path"] = Url_["path"]
	}
	return options;
}
//options-使用optionsIP后的optionsIP
function locationSet(location, options, httpifhttps = false) {
	if (location.indexOf("http://") == -1 && location.indexOf("https://") == -1) {
		if (httpifhttps == false) {
			//http
			let Httpslocation = urlData.parse(options["hostname"])
			if (Httpslocation["protocol"] == undefined || Httpslocation["protocol"] == null) {
				Httpslocation["protocol"] = "http:"
			}
			if (Httpslocation["host"] == undefined || Httpslocation["host"] == null) {
				Httpslocation["host"] = options["hostname"]
			}
			if (Httpslocation["port"] == undefined || Httpslocation["port"] == null) {
				Httpslocation["port"] = 80
			}
			location = location.replace(Httpslocation["host"], "")
			if (Httpslocation["port"] == 80) {
				location = Httpslocation["protocol"] + "//" + Httpslocation["host"] + location
			} else {
				location = Httpslocation["protocol"] + "//" + Httpslocation["host"] + ":" + Httpslocation["port"] + location
			}
		} else {
			let Httpslocation = urlData.parse(options["hostname"])
			if (Httpslocation["protocol"] == undefined || Httpslocation["protocol"] == null) {
				Httpslocation["protocol"] = "https:"
			}
			if (Httpslocation["host"] == undefined || Httpslocation["host"] == null) {
				Httpslocation["host"] = options["hostname"]
			}
			if (Httpslocation["port"] == undefined || Httpslocation["port"] == null) {
				Httpslocation["port"] = 80
			}
			location = location.replace(Httpslocation["host"], "")
			if (Httpslocation["port"] == 80) {
				location = Httpslocation["protocol"] + "//" + Httpslocation["host"] + location
			} else {
				location = Httpslocation["protocol"] + "//" + Httpslocation["host"] + ":" + Httpslocation["port"] + location
			}
		}
	}
	return location;
}