/**
 * Created by rockyl on 2019-12-20.
 */
import {clonePureObj, newScriptContent, typeMapping} from "../../utils";
import {divideCode} from "zeroing-code-divider";
import {generateLibraryScriptEl, fillTemplate, generateJsScriptEl} from "zeroing-template-fill";
import db from "../../utils/db-storage";

const storeName = 'preview';

let codesCache = {};
let urlsCache = {};

function getPackages(packages) {
	return async function (schema, type) {
		let ids = Object.keys(schema);
		let result = ids.map(pid=>{
			let packageItem = packages[typeMapping[type]][pid];
			return {
				data: packageItem,
			};
		}).filter(item=>!!item);
		return result;
	}
}

export async function preprocess(project, packages) {
	let data = JSON.parse(project.data);
	resetScrollType(data.views[0])
	const codes = await divideCode(data, {
		debug: true,
		getPackages: getPackages(packages),
		dependencies: data.dependencies,
	});

	let {options: {tpl, pageTitle, containerId}, dependencies} = data;

	let scripts = [];
	for (let key in codes) {
		let oldCode = codesCache[key];
		let code = codes[key];
		let url;
		if (oldCode !== code) {
			url = urlsCache[key] = URL.createObjectURL(new Blob([code]));
		} else {
			url = urlsCache[key];
		}
		scripts.push(url);
	}
	scripts = scripts.map(item => generateJsScriptEl(item));
	scripts.push(newScriptContent('var proxy_mode=true;'));
	codesCache = codes;

	const dataUrl = URL.createObjectURL(new Blob([JSON.stringify(data)]));

	const {libraryScriptElMap, analyseResult} = await generateLibraryScriptEl(tpl, dependencies, getPackages(packages), '//yun.duiba.com.cn/editor/zeroing/libs/', true);

	tpl = fillTemplate(tpl, {
		pageTitle,
		containerId,
		scripts: scripts.join('\n'),
		libraries: libraryScriptElMap,
	});

	tpl = tpl.replace('//yun.duiba.com.cn/aurora/$VERSION$-data.json', dataUrl);
	console.log("塞入数据",storeName,data)

	db.set(storeName, {
		id: project.id,
		data,
		tpl,
	});
	localStorage.setItem('preview-ts', Date.now().toString());

	//重置编辑视图数据为实际视图数据
	function resetScrollType(data) {
		if(data.type=="editScrollList"){
			data.type="scrollList"
		}
		if(data.type=="editScrollView"){
			data.type="scrollView"
		}
		if(data.children){
			for(let i=0;i<data.children.length;i++){
				resetScrollType(data.children[i])
			}
		}
	}
}
