package goPress

import (
	"github.com/hoisie/web"
	"io/ioutil"
	"log"
	"os"
)

//
// Function:          GetStylesheets
//
// Description:       This function is used to produce the stylesheet to the user.
//
// Inputs:
//
func GetStylesheets(ctx *web.Context) string {
	//
	// See if we have already loaded them or not. If so, just return the pre-loaded
	// stylesheet.
	//
	ctx.SetHeader("Content-Type", "text/css", true)
	SetStandardHeader(ctx)
	tmp := ""
	if SiteData.stylesheet == "" {
		tmp = LoadFile(SiteData.Sitebase + "css/final/final.css")
		//
		// If we are testing, we do not want the server to cache the
		// stylesheets. Therefore, if compile is true, cache them. Otherwise,
		// do not.
		//
		if SiteData.Cache == true {
			SiteData.stylesheet = tmp
		}
	} else {
		//
		// We have a cached style sheet. Send it to the browser.
		//
		tmp = SiteData.stylesheet
	}

	//
	// Return the stylesheet.
	//
	return tmp
}

//
// Function:          GetScripts
//
// Description:       This function is to load JavaScripts to the browser. This will
//                    actually load all the JavaScript files into one compressed file
//                    for uploading to the browser.
//
// Inputs:
//
func GetScripts(ctx *web.Context) string {
	//
	// See if we have already loaded them or not. If so, just return the pre-loaded
	// scripts.
	//
	ctx.SetHeader("Content-Type", "text/javascript", true)
	SetStandardHeader(ctx)
	tmp := ""
	if SiteData.scripts == "" {
		tmp = LoadFile(SiteData.Sitebase + "js/final/final.js")

		//
		// If we are testing, we do not want the server to cache the
		// stylesheets. Therefore, if compile is true, cache them. Otherwise,
		// do not.
		//
		if SiteData.Cache == true {
			SiteData.scripts = tmp
		}
	} else {
		//
		// We have a cached style sheet. Send it to the browser.
		//
		tmp = SiteData.scripts
	}

	//
	// Return the resulting compiled stylesheet.
	//
	return tmp
}

//
// Function:		 LoadFile
//
// Description:		 This function if for loading individual file contents.
//
// Inputs
//					 file          name of the file to be loaded
//
func LoadFile(file string) string {
	ret := ""
	log.Println("Loading file: " + file)
	wfile, err := os.Open(file)
	if err == nil {
		bcontents, err := ioutil.ReadAll(wfile)
		err = err
		ret = string(bcontents)
		wfile.Close()
	} else {
		//
		// Could not read the file.
		//
		log.Println("Could not read: " + file)
	}
	return ret
}
