// plugin/vue-renderer/renderer/compileVueFile.js
import fs from 'fs'
import pug from 'pug'
import * as sass from 'sass'
import { compileStyle } from '../vuelib.js'
import { compileVueComponent, setDefaultVuePath } from './compileVueComponent.js'
export { setDefaultVuePath }

function parseBeforeLast(subjectString, separator) {
	if (subjectString == null) {
		return subjectString
	}
	let pos = subjectString.lastIndexOf(separator)
	if (pos >= 0) {
		return subjectString.substring(0, pos)
	}
	return subjectString
}

let styleId = 0

export function compileVueFile(srcPath, fileName, newComponentPath, ssr, sourceMap = false, vapor = false) {
	let js
	if (fs.existsSync(newComponentPath + fileName + '.js')) {
		fileName = newComponentPath + fileName + '.js' // maybe manually fixed existing file
	} else {
		console.log(`🚀 compileVueFile.js ~ creating file:`, newComponentPath + fileName + '.js')
		let html
		if (fs.existsSync(srcPath + fileName)) {
			js = fs.readFileSync(srcPath + fileName.replace('.html', '.js'), 'utf-8')
			html = fs.readFileSync(srcPath + fileName, 'utf-8')
		} else {
			js = fs.readFileSync(srcPath + fileName + '.vue', 'utf-8')
		}
		const ret = compileVueComponent({ file_name: fileName, js, html, pug, ssr, source_map: sourceMap, style: true, vapor })
		const styleArr = []
		const scopedStyleArr = []
		for (const item of ret.style) {
			let css = item.content
			if (item.lang === 'scss' || item.lang === 'sass') {
				const result = sass.compileString(css)
				css = result.css.toString()
			}
			styleId++
			const style = compileStyle({ id: 'nc-style-' + styleId, source: css, filename: fileName })
			if (item.scoped) {
				scopedStyleArr.push(style.code)
			} else {
				styleArr.push(style.code)
			}
		}
		if (scopedStyleArr.length > 0) {
			console.log(`* component '${fileName}' scoped style:\n${scopedStyleArr}`)
			// TODO: add to ../component/core/nc-component-style.json
		}
		if (styleArr.length > 0) {
			console.log(`* component '${fileName}' style:\n${styleArr}`)
			// TODO: add to ../component/core/nc-component-style.json
		}
		const path = parseBeforeLast(fileName, '/')
		if (path !== fileName && !fs.existsSync(newComponentPath + path)) {
			fs.mkdirSync(newComponentPath + path)
		}
		fileName = newComponentPath + fileName + '.js'
		fs.writeFileSync(fileName, ret.code)
		// console.log(`🚀 compileVueFile.js ~ created file:`, fileName)
	}
	/*
	// import(dataUri) does needs full path for access to existing files: `import { fn } from 'file:///${process.cwd()}/dyn-import-existing.js'; fn(10);`
	// https://2ality.com/2019/10/eval-via-import.html
	const dataUri = 'data:text/javascript;charset=utf-8,' + encodeURIComponent(code)
	const ret = await import(dataUri)
	*/
	const ret = import(fileName)
	console.log(`🚀 compileVueFile.js ~ imported file:`, fileName)
	return ret
}
