package main

import (
	"fmt"
	"log"

	"github.com/blevesearch/bleve"
)

// QuoteIndex index of quotes
type QuoteIndex struct {
	index       bleve.Index
	Videos      []Quote
	videoByPage map[string]Quote //videoByPage[youtubeKey]
}

// Search search quote in index
func (si *QuoteIndex) Search(str string) ([]Quote, error) {
	var resp []Quote

	query := bleve.NewMatchQuery(str)
	req := bleve.NewSearchRequest(query)
	searchResults, err := si.index.Search(req)
	if err != nil {
		return nil, fmt.Errorf("Request error %w", err)
	}
	for _, hit := range searchResults.Hits {
		if sound, ok := si.videoByPage[hit.ID]; ok {
			resp = append(resp, sound)
		}
	}

	if len(resp) == 0 {
		return nil, fmt.Errorf("Quote not found")
	}

	return resp, nil
}

func indexQuotes(quotes []Quote) (*QuoteIndex, error) {
	quoteMap := make(map[string]Quote)

	mapping := bleve.NewIndexMapping()
	mapping.DefaultAnalyzer = mapping.FieldAnalyzer("french")
	index, err := bleve.NewMemOnly(mapping)
	if err != nil {
		return nil, fmt.Errorf("Could not creat index: %w", err)
	}

	for _, quote := range quotes {
		if index.Index(quote.Page, quote.Quote) != nil {
			log.Printf("Error indexing %v\n", quote.Quote)
		}
		quoteMap[quote.Page] = quote
	}

	return &QuoteIndex{
		index,
		quotes,
		quoteMap,
	}, nil
}
