module web

import freeflowuniverse.crystallib.core.playbook
import veb
import web.components.carousel
import freeflowuniverse.crystallib.ui.console
import os

pub fn render(mut ctx Context) !map[string]string {
	mut components := map[string]string{}
	
	mut plbook := playbook.new(text: carousel.example_heroscript)!
	carousels := carousel.play(mut plbook)!

	for key, carousel in carousels {
		if key in components {
			panic('this should never happen')
		}
		components[key] = carousel.html()
	}

	//todo: here we need to add all renders we support
	// if true{
	// 	println(res)
	// 	exit(1)
	// }

	return components
}

pub fn template_render(path string, content map[string]string)!string {
	mut name:=os.base(path).to_lower()
	name=name.all_before_last(".html")
	c := match name{
		"index"{
			$tmpl('./templates/index.html')
		}"blog-list-classic"{
			$tmpl('./templates/blog-list-classic.html')		
		}else{
			return error("can't find template with name: ${name}")
		}
	}
	//TODO: NEED to add the other templates, its a pitty we can't do this dynamic
	return c
}

pub fn (mut app App) index(mut ctx Context) veb.Result {
	return app.index2(mut ctx ,"")
}

@['/:path']    
pub fn (mut app App) index2(mut ctx Context,path string) veb.Result {
	mut templpath:="${path}"
	if templpath==""{
		templpath="index"
	}
	println(templpath)
	console.print_debug("templpath : '${templpath}'")
	
	content:=render(mut ctx) or { 
		ctx.res.set_status(.unknown)
		return ctx.html('<h1>ERROR!</h1>${err}')
	}
	// mut tmp_var := map[string]dtm.DtmMultiTypeMap{}
	// for key,val in content{
	// 	tmp_var[key] = val
	// }
	//t:=app.dtm.expand(templpath,placeholders:&tmp_var)
	t:= template_render(templpath,content)or { 
		ctx.res.set_status(.unknown)
		return ctx.html('<h1>ERROR TEMPLATE!</h1>${err}')
	}
	return ctx.html(t)
}

