/**
 * Created by rockyl on 2019-12-18.
 */

import db from "../../utils/db-storage";
import {getMockServeEnabled} from "../../utils";

db.open();

const logStyle = "color: rgb(63, 172, 203)";

export function applyMock(projectID, win) {
	win.mock = function ({url, method, params = {}, type}, callback, resolve, reject) {
		const mockServeEnabled = getMockServeEnabled(projectID);
		if (!mockServeEnabled) {
			callback();
			return;
		}

		if(url.includes('projectx')){
			url = url.replace(/projectx\/\w+\//, '');
		}

		db.get('mock', url)
			.then(
				rule => {
					if (rule && !rule.disabled) {
						const {timeout = 0, successRatio = 1, data} = rule;
						setTimeout(function () {
							if (Math.random() < successRatio) {
								try {
									console.log(`%c[mock] ${url} ${method} ${JSON.stringify(params)}`, logStyle, JSON.parse(data));
									resolve(JSON.parse(data));
								} catch (e) {
									reject(e);
								}
							} else {
								reject(url + ' 404 (Not Found)')
							}
						}, timeout);
						callback(rule);
					} else {
						callback();
					}
				},
				e => {
					callback();
				}
			);
	};
}