package main

import (
	"./src/goPress"
	"fmt"
	"github.com/hoisie/web"
	"github.com/microcosm-cc/bluemonday"
	"net/smtp"
)

//
// Function:          main
//
// Description:       This is the main function that is called whenever the program is
//                    executed. It will load the globals, set the different routes, and
//                    start the server.
//
// Inputs:
//
func main() {
	//
	// Load the default Shortcodes.
	//
	goPress.LoadDefaultShortcodes()

	//
	// Load all global variables.
	//
	goPress.GetGlobals()

	//
	// Setup the Default routes.
	//
	goPress.DefaultRoutes()

	//
	// Setup special route for our form processing.
	//
	goPress.SetPostRoute("/api/message", postMessage)

	//
	// Run the web server
	//
	goPress.StartServer(goPress.SiteData.ServerAddress)
}

//
// Function:         postMessage
//
// Description:      This function will send the message from them
//                   the website to the owner of the site.
//
// Inputs:
//                   ctx     The web server context.
//
func postMessage(ctx *web.Context) string {
	//
	// Get the post information and send the email.
	//
	name := ctx.Params["Name"]
	from := ctx.Params["Email"]
	p := bluemonday.UGCPolicy()
	message := p.Sanitize(ctx.Params["Message"])
	to := "<your email address>"
	subject := "Message from User:" + name + " of CustomCT.com"
	sendEmail(to, from, subject, message)

	//
	// Get the messagesent page contents and process it.
	//
	pgloc := goPress.SiteData.Sitebase + "pages/messagesent"
	return goPress.RenderPageContents(ctx, goPress.GetPageContents(pgloc), pgloc)
}

//
// Function:         sendEmail
//
// Description:      This function sends an email message.
//
// Inputs:
//                   to      The email address to send the message
//                   from    The email address of the person sending the message
//                   subject The subject of the message
//                   message The message of the email
//
func sendEmail(to string, from string, subject string, message string) {
	body := fmt.Sprintf("To: %s\r\nSubject: %s\r\n\r\n%s", to, subject, message)
	auth := smtp.PlainAuth("", "<your email address>", "<your password>", "smtp.gmail.com")
	err := smtp.SendMail("smtp.gmail.com:587", auth, from, []string{to}, []byte(body))
	if err != nil {
		//
		// Process the error. Currently, assuming there isn't a problem.
		//
	}
}
