// plugin/vue-renderer/renderer/render-page-promise.js
// idea taken from: https://lachlan-miller.me/articles/vue-3-pdf-customer-renderer
// TODO: async is not implemented correnctly in spidermonkey/src/spiderjs.cpp, see: https://stackoverflow.com/questions/22698268/asynchronously-calling-a-callback-function-in-spidermonkey-js-engine

import fs from 'fs'
import { renderPageApp } from './render-page-app.js'

const componentArray = []

export async function loadComponent(param) {
	let startTime = Date.now()
	const elementArr = param.element_array /* ['nc-form/nc-form', 'nc-form/nc-row', 'nc-form/nc-col', ...] */
	const componentPath = '../component/'
	const componentPromise = []
	elementArr.forEach(fileName => {
		componentPromise.push(import(componentPath + fileName + '.js'))
	})
	const importPromise = Promise.allSettled(componentPromise).then(ret => {
		let i = 0
		ret.forEach(item => {
			// if (item && item.default) { // for Promise.all
			if (item.status == 'fulfilled') {
				item = item.value // for Promise.allSettled
				if (item.ssrRender) {
					item.default.ssrRender = item.ssrRender
				} else if (!item.default.render) {
					item.default.render = item.render
				}
				componentArray.push(item.default)
			} else {
				console.error('importing compiled vue component ' + componentPath + elementArr[i] + '.js' + ' failed, error: ', (item.reason && item.reason.message) || item)
				componentArray.push({})
			}
			i++
		})
	})
	await importPromise
	startTime = Date.now() - startTime
	const msg = '••• importing ' + componentArray.length + ' compiled vue components succeeded in ' + (startTime / 1000).toFixed(4) + ' seconds •••\n'
	console.log('%c' + msg, 'font-weight: bold; font-style: italic;')
	return msg
}

export function renderPage(param) {
	return renderPageApp(componentArray, param)
}

const elementArr = JSON.parse(fs.readFileSync('./element-arr.json', 'utf8')).element
loadComponent({ element_array: elementArr })
