package controllers

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"

	OCCatalog_cli "oc-search/api-client/oc-catalog"

	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"

	"oc-search/models"
)

// SearchController is the controller in chrage of solr
type SearchController struct {
	beego.Controller
}

func loadSingleFile(filename string) []models.Resource {
	var list []models.Resource
	jsonFile, err := os.Open(filename)
	// if we os.Open returns an error then handle it
	if err != nil {
		fmt.Println(err)
	}
	defer jsonFile.Close()
	byteValue, _ := ioutil.ReadAll(jsonFile)
	json.Unmarshal(byteValue, &list)
	return list
}

// Get implements simple search
func (c *SearchController) Get() {

	logs.Debug("received : %v",c.Ctx.Input.RequestBody)
	

	query := c.GetString("q")

	var resources OCCatalog_cli.ModelsSearchResult

	//FIXME: dashboard special case for x_dash.json ?????
	resources, _, err := OCCatalogAPI.SearchApi.SearchControllerSearchByWord(context.Background(), query)
	if err != nil {
		logs.Warn(err.Error())
		return
	}

	//TODO: Adapt the View and models to use the OCCatalog_cli models as much as possible

	c.Data["list"] = resources
	c.TplName = "search.tpl"
}
