package appshell

import (
	"encoding/json"
	"esperframework/options"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
)

func GetAppShellHTML(l *ASLexer) []byte {
	path := filepath.Join(l.Options.AppPath, "__app.html")

	if _, err := os.Stat(path); os.IsNotExist(err) {
		wd, err := os.Getwd()
		if err != nil {
			log.Fatalf("\nFailed to get working directory while getting app shell HTML\n%s\n", err)
		}

		templatePath := filepath.Join(wd, "../", "src", "templates", "__app.tmpl.html")
		file, err := ioutil.ReadFile(templatePath)
		if err != nil {
			log.Fatalf("\nFailed to read app shell template at %s\n%s\n", templatePath, err)
		}
		return file
	}

	file, err := os.ReadFile(path)
	if err != nil {
		log.Fatalf("\nFailed to read app shell file at %s\n%s\n", path, err)
	}

	return file
}

func GetAppShellJSON(opts *options.Options) ASTree {
	aSh, err := ioutil.ReadFile(filepath.Join((*opts).CachePath, "__app.json"))
	if err != nil {
		log.Fatalf("\nFailed to read app shell file at path %s\n%s\n", filepath.Join(opts.CachePath, "__app.json"), err)
	}

	var as ASTree
	err = json.Unmarshal(aSh, &as)
	if err != nil {
		log.Fatalf("\nFailed to unmarshal __app.json\n%s\n", err)
	}

	return as
}
