// plugin/vue-renderer/renderer/compileVueComponent.js
import { replaceContent } from './replace-content.js'
import { parse, compileScript, compileTemplate } from '../vuelib.js' // '@vue/compiler-sfc'

// inject,
let defaultVuePath = '/vue.js'
let id = 10000

export function setDefaultVuePath(path) {
	defaultVuePath = path
}

let jsStart
export function setJsStart() {
	if (defaultVuePath === '../vuelib.js') {
		// called from render-compile.js
		jsStart = `// created by render-compile.js and compileVueComponent.js
`
		return
	}
	jsStart = `
import { getCurrentInstance, inject, provide, ref, reactive, computed, watch, watchEffect, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onActivated, onDeactivated } from '${defaultVuePath}'
import { _ as nc } from '/assets/nc-plugin.js'
const dt = nc.dt
const message = nc.message
const peg = nc.peg
`
}

export function compileVueComponent(param) {
	let { file_name, js, html, pug, ssr, vue_path, base_path, style, source_map, vapor } = param
	if (!jsStart) {
		setJsStart()
	}
	if (source_map !== true) {
		source_map = false
	}
	vue_path = vue_path || defaultVuePath
	base_path = base_path || ''
	if (ssr !== true) {
		ssr = false
	}
	const fileNameVue = file_name + '.vue'
	let content
	if (typeof html === 'string') {
		content = '<template>\n' + html + '</template>\n\n' + '<script setup>\n' + jsStart + js + '\n</script>\n'
	} else {
		content = jsStart + js // .vue component from disk
	}
	const parsed = parse(content, {
		vapor: vapor,
		isProd: true,
		sourceMap: source_map,
		filename: fileNameVue
	})
	id++
	// console.log(`🚀 ~ file: compileVueComponent.js:43 ~ content:`, parsed.descriptor)
	// console.log does not show in nc-server terminal, debug using: throw new Error("parsed.descriptor: '"+JSON.stringify(parsed.descriptor)+"'")
	const script = compileScript(parsed.descriptor, {
		vapor: vapor,
		inlineTemplate: true,
		isProd: true,
		id: 'nc-script-' + id,
		filename: fileNameVue,
		sourceMap: source_map
	})
	const ret = {}
	if (parsed.descriptor.template) {
		let parsedHtml = parsed.descriptor.template.content
		if (parsed.descriptor.template.lang === 'pug') {
			if (!pug) {
				ret.error = 'pug is not defined, give it as param 4'
			} else {
				const pugOptions = {}
				const fn = pug.compile(parsedHtml, pugOptions)
				const pugLocals = {}
				parsedHtml = fn(pugLocals)
			}
		}
		if (html === true) {
			ret.html = parsedHtml
		}
		id++
		// render = compile(parsedHtml) // works, but gives a function, not code as text
		const render = compileTemplate({
			vapor: vapor,
			sourceMap: source_map,
			id: 'nc-template-' + id,
			source: parsedHtml,
			filename: fileNameVue,
			isProd: true,
			ssr: ssr
		})
		if (defaultVuePath === '../vuelib.js') {
			// called from render-compile.js when creating printing components
			if (script.content) {
				script.content = script.content.replace('export default {', 'export default { render: render, ')
				ret.code = replaceContent(file_name, script.content + '\n\n// render code\n' + render.code) // , vue_path)
			} else {
				ret.code = replaceContent(file_name, '// warning: no script content\n\n// render code\n' + render.code)
			}
		} else {
			ret.code = replaceContent(file_name, script.content, vue_path, base_path)
		}
	}
	if (style) {
		ret.style = parsed.descriptor.styles
		return ret
	}
	return ret.code
}

/*
function parseVueComponent(param) {
	let { file_name, content, pug, sass, vue_path } = param
	vue_path = vue_path || defaultVuePath
	const parsed = parse(content, { source_map: false, filename: file_name + '.vue' })
	const ret = {}
	if (parsed.errors.length > 0) {
		ret.error = parsed.errors.join('\n')
	}
	if (parsed.descriptor.script) {
		if (parsed.descriptor.scriptSetup) {
			ret.code = parsed.descriptor.scriptSetup.content
		} else {
			ret.code = parsed.descriptor.script.content
		}
	}
	if (parsed.descriptor.styles && parsed.descriptor.styles.length > 0) {
		let scopedStyleArr = []
		let styleArr = []
		for (const item of parsed.descriptor.styles) {
			let css = item.content
			if (item.lang === 'scss' || item.lang === 'sass') {
				const result = sass.renderSync({ data: css })
				css = result.css.toString()
			}
			const style = compileStyle({ id: 'nc-style-' + id, source: css, filename: file_name })
			if (item.scoped) {
				scopedStyleArr.push(style.code)
			} else {
				styleArr.push(style.code)
			}
		}
		if (scopedStyleArr.length > 0) {
			ret.scoped_style = scopedStyleArr
		}
		if (styleArr.length > 0) {
			ret.style = styleArr
		}
	}
	if (parsed.descriptor.template) {
		let parsedHtml = parsed.descriptor.template.content
		if (parsed.descriptor.template.lang === 'pug') {
			if (!pug) {
				ret.error = 'pug is not defined, give it as param'
			} else {
				const pugOptions = {}
				const fn = pug.compile(parsedHtml, pugOptions)
				const pugLocals = {}
				parsedHtml = fn(pugLocals)
			}
		}
		ret.html = parsedHtml
	}
	return ret
} */
