/**
 * Created by rockyl on 2018/11/9.
 *
 * 常用工具
 */

export function injectProp(target: any, data?: any, callback?: Function, ignoreMethod: boolean = true, ignoreNull: boolean = true): boolean {
	if (!target || !data) {
		return false;
	}

	let result = true;
	for (let key in data) {
		let value: any = data[key];
		if ((!ignoreMethod || typeof value != 'function') && (!ignoreNull || value != null)) {
			if (callback) {
				callback(target, key, value);
			} else {
				target[key] = value;
			}
		}
	}
	return result;
}

export function objectStringify(obj) {
	if (!obj) {
		return '';
	}
	let arr = [];
	for (let key in obj) {
		arr.push(key + '=' + obj[key]);
	}
	return arr.join('&');
}

export function waitPromise(duration): Promise<void> {
	return new Promise(resolve => {
		setTimeout(resolve, duration);
	});
}

export function format(formatStr: string, ...params): string {
	return formatApply(formatStr, params);
}

export function formatApply(formatStr: string, params: any[]): string {
	let result: string = formatStr;
	for (let i = 0, len = params.length; i < len; i++) {
		let reg = new RegExp("\\{" + i + "\\}", 'g');
		result = result.replace(reg, params[i]);
	}

	return result;
}

const zeros: Array<string> = [
	"0",
	"00",
	"000",
	"0000",
	"00000",
	"000000",
	"0000000",
	"00000000",
	"000000000",
	"0000000000"
];

export function supplement(value: number, count: number): string {
	let index = count - value.toString().length - 1;
	if (index < 0) {
		return value.toString();
	}
	return zeros[index] + value;
}
