// Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module tmpl
import os
import strings
const (
	str_start = "sb.write_string('"
	str_end   = "' ) "
)
// compile_file compiles the content of a file by the given path as a template
pub fn compile_file(path string, fn_name string) string {
	basepath := os.dir(path)
	html := os.read_file(path) or { panic('html failed') }
	return compile_template(basepath, html, fn_name)
}
enum State {
	html
	css // ' {
			state = .html
		} else if line == '' {
			state = .html
		}
		if line.contains('@include ') {
			lines.delete(i)
			mut file_name := line.split("'")[1]
			mut file_ext := os.file_ext(file_name)
			if file_ext == '' {
				file_ext = '.html'
			}
			file_name = file_name.replace(file_ext, '')
			// relative path, starting with the current folder
			mut templates_folder := os.real_path(basepath)
			if file_name.contains('/') && file_name.starts_with('/') {
				// an absolute path
				templates_folder = ''
			}
			file_path := os.real_path(os.join_path(templates_folder, '$file_name$file_ext'))
			$if trace_tmpl ? {
				eprintln('>>> basepath: "$basepath" , fn_name: "$fn_name" , @include line: "$line" , file_name: "$file_name" , file_ext: "$file_ext" , templates_folder: "$templates_folder" , file_path: "$file_path"')
			}
			file_content := os.read_file(file_path) or {
				panic('Vweb: reading file $file_name from path: $file_path failed.')
			}
			file_splitted := file_content.split_into_lines().reverse()
			for f in file_splitted {
				lines.insert(i, f)
			}
			i--
		} else if line.contains('@js ') {
			pos := line.index('@js') or { continue }
			s.write_string('')
		} else if line.contains('@css ') {
			pos := line.index('@css') or { continue }
			s.write_string('')
		} else if line.contains('@if ') {
			s.writeln(tmpl.str_end)
			pos := line.index('@if') or { continue }
			s.writeln('if ' + line[pos + 4..] + '{')
			s.writeln(tmpl.str_start)
		} else if line.contains('@end') {
			// Remove new line byte
			s.go_back(1)
			s.writeln(tmpl.str_end)
			s.writeln('}')
			s.writeln(tmpl.str_start)
		} else if line.contains('@else') {
			// Remove new line byte
			s.go_back(1)
			s.writeln(tmpl.str_end)
			s.writeln(' } else { ')
			s.writeln(tmpl.str_start)
		} else if line.contains('@for') {
			s.writeln(tmpl.str_end)
			pos := line.index('@for') or { continue }
			s.writeln('for ' + line[pos + 4..] + '{')
			s.writeln(tmpl.str_start)
		} else if state == .html && line.contains('span.') && line.ends_with('{') {
			// `span.header {` => `