import * as _lunr from 'lunr';
import * as _lunr_stemmer from 'lunr-languages/lunr.stemmer.support';
import * as _lunr_de from 'lunr-languages/lunr.de';

const createSearchIndex = (documents, raf, fields, lang) => {

    const searchIndex = () => {

        let lunr = _lunr.default;

        // Create search index. We need *this*
        searchIndex.idx = lunr(function() {
            if (lang === 'de') {
                _lunr_stemmer.default(lunr);
                _lunr_de.default(lunr);
                this.use(lunr.de);
            }

            this.ref(raf);
            for (let field of fields) {
                this.field(field);
            }

            documents.forEach(doc => {
                this.add(doc);
            });
        });
    };

    /**
     * Compile search string
     * @param input: String to search for
     * @returns: Compiled search string
     *
     * Input is split into <words>, which are surrounded by asterisks
     * (<word> may be anywhere in the searched text)
     * and prefixed with a '+' (AND combination of multiple search terms)
     */
    searchIndex.compileString = (input) => {

        let result = '';
        if (input.length >= 3) {

            let sstring = [];
            const words = input.trim().split(' ');

            for (let word of words) {
                if (word.length >= 3) {
                    sstring.push('+*' + word + '*');
                }
            }
            result = sstring.join(' ');
        }
        return result;
    };

    searchIndex.searchFor = (string) => {
        let qs = searchIndex.compileString(string);
        let sresults = [];
        if (qs.length >= 3) {
            sresults = searchIndex.idx.search(qs);
        }

        let searchResults = [];
        sresults.forEach(result => {
            let entry = documents.find(e => e.index === parseInt(result.ref));
            entry.score = result.score;
            searchResults.push(entry);
        });

        return searchResults;
    };

    searchIndex();
    return searchIndex;
};

export default createSearchIndex;
