package org.hso.ecommerce.action.shop;

import org.hso.ecommerce.entities.shop.Article;
import org.hso.ecommerce.repos.shop.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SearchByTermAction {

    public static List<Article> searchByTerm(String sourceTerm, ArticleRepository repository) {

        List<String> terms = Arrays.asList(sourceTerm.split(" "));
        List<Article> resultArticles = new ArrayList<>();

        terms.forEach(term -> {
            List<Article> titleArticles = repository.getArticlesByTermInTitle(term); //search in Title
            titleArticles.forEach(article -> {
                if(!resultArticles.contains(article)){
                    resultArticles.add(article);
                }
            });

        });

        terms.forEach(term -> {
            List<Article> descArticles = repository.getArticlesByTermInDescription(term); //search by Term
            descArticles.forEach(article -> {
                if(!resultArticles.contains(article)){
                    resultArticles.add(article);
                }
            });

        });

        return resultArticles;
    }
}
