package cz.inqool.dl4dh.krameriusplus;

import com.fasterxml.jackson.annotation.JsonProperty;
import cz.inqool.dl4dh.krameriusplus.domain.entity.page.Token;
import lombok.Getter;
import lombok.Setter;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Norbert Bodnar
 */
@Getter
@Setter
//TODO: only for Solr, delete later
public class SolrPreAnalyzedField {

    @JsonProperty("v")
    private String version = "1";

    @JsonProperty("str")
    private String storedValue;

    @JsonProperty("tokens")
    private List<SolrToken> tokens;

    public SolrPreAnalyzedField(List<Token> tokens) {
        StringBuilder stringBuilder = new StringBuilder();

        for (Token token : tokens) {
            stringBuilder.append(token.getContent());

            if (!token.getLinguisticMetadata().getMisc().contains("SpaceAfter=No")) {
                stringBuilder.append(" ");
            }
        }

        this.storedValue = stringBuilder.toString().strip();

        this.tokens = tokens.stream()
                .map(token -> {
                    String payload = null;

                    String tokenUPosTag = token.getLinguisticMetadata().getUPosTag();
                    // if token is a NOUN or ADJ, payload is in format "NUMBER|CASE"
                    if (tokenUPosTag.equals("NOUN") || tokenUPosTag.equals("ADJ")) {
                        payload = String.join("|",
                                token.getLinguisticMetadata().getNumber(), token.getLinguisticMetadata().getCase());
                    }
                    // if token is a VERB, payload is in format "NUMBER|PERSON"
                    else if (tokenUPosTag.equals("VERB")) {
                        payload = String.join("|",
                                token.getLinguisticMetadata().getNumber(), token.getLinguisticMetadata().getPerson());
                    }

                    return new SolrToken(
                            token.getLinguisticMetadata().getLemma(),
                            token.getStartOffset(),
                            token.getEndOffset(),
                            payload == null ? "" : payload);
                })
                .collect(Collectors.toList());
    }
}
