package routes

// |@@| C

import (
	"gardening/src/lib/searcher"
	"gardening/src/srv/searchers"
	"github.com/gin-gonic/gin"
	"gitlab.com/ccyrillee/kitcla/goc"
)

type SearchAjxRoute struct {
	Searcher  *searcher.Searcher
	Searchers *searchers.Searchers
}

type SearchItem struct {
	Html string
	Url  string
}

func (this *SearchAjxRoute) Act(c *gin.Context) {
	if this.Searcher.IsIndexing() {
		c.JSON(200, gin.H{"msg": "indexing", "items": []searcher.SearchValue{}})
		return
	}
	if !this.Searcher.IsReady() {
		this.Searcher.Indexing(c, this.Searchers.Indexing)
	}
	search := &struct {
		Search string
		Kind   string
		Scope  []*searcher.ScopeItem
	}{}
	c.BindJSON(search)
	values := this.Searcher.SearchValues(c, search.Kind, search.Search, search.Scope)
	components := this.Searchers.GetSearchItems(c, values)
	var items []SearchItem
	for i, component := range components {
		html := goc.RenderRoot(component)
		item := SearchItem{Html: html, Url: values[i].Url}
		items = append(items, item)
	}
	c.JSON(200, gin.H{"items": items})
}
