package controllers

import (
	"net/http"
	"strconv"

	"git.kirsle.net/apps/gophertype/pkg/models"
	"git.kirsle.net/apps/gophertype/pkg/responses"
	"git.kirsle.net/apps/gophertype/pkg/search"
	"git.kirsle.net/apps/gophertype/pkg/session"
)

// BlogSearch at "/blog/search" for searching blog entries.
func BlogSearch(w http.ResponseWriter, r *http.Request) {
	var (
		query   = r.FormValue("q")
		pageStr = r.FormValue("page")
		page    int
	)

	if a, err := strconv.Atoi(pageStr); err == nil {
		page = a
	}

	// Parse their search string (includes and excludes)
	search := search.ParseSearchString(query)

	pp, err := models.Posts.SearchPosts(search, page, 24)
	if err != nil {
		session.FlashError(w, r, "Error searching posts: %s", err)
		responses.Redirect(w, r, "/")
		return
	}

	v := responses.NewTemplateVars(w, r)
	v.V["posts"] = pp
	v.V["search"] = query
	v.V["terms"] = search

	responses.RenderTemplate(w, r, "_builtin/blog/search.gohtml", v)
}
