/* UtilLib - Copyright (c) 2011-2017 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.conditions;

import java.text.RuleBasedCollator;
import net.mapeadores.util.exceptions.SwitchException;
import net.mapeadores.util.text.collation.CollationUnit;


/**
 *
 * @author Vincent Calame
 */
public class CollatedStringTestUnit {

    private final TextTest textTest;
    private final String searchCollatedString;

    private CollatedStringTestUnit(TextTest textTest, String searchCollatedString) {
        this.textTest = textTest;
        this.searchCollatedString = searchCollatedString;
    }

    public TextTest getTextTest() {
        return textTest;
    }

    public boolean accept(String collatedString) {
        switch (textTest.getTestType()) {
            case ConditionsConstants.EMPTY_TEST:
                return (collatedString.length() == 0);
            case ConditionsConstants.NOT_EMPTY_TEST:
                return (collatedString.length() > 0);
            case ConditionsConstants.NOT_MATCHES_TEST:
                return !collatedString.equals(searchCollatedString);
            case ConditionsConstants.NOT_STARTSWITH_TEST:
                return !collatedString.startsWith(searchCollatedString);
            case ConditionsConstants.NOT_ENDSWITH_TEST:
                return !collatedString.endsWith(searchCollatedString);
            case ConditionsConstants.NOT_CONTAINS_TEST:
                return !collatedString.contains(searchCollatedString);
            case ConditionsConstants.MATCHES_TEST:
                return collatedString.equals(searchCollatedString);
            case ConditionsConstants.STARTSWITH_TEST:
                return collatedString.startsWith(searchCollatedString);
            case ConditionsConstants.ENDSWITH_TEST:
                return collatedString.endsWith(searchCollatedString);
            case ConditionsConstants.CONTAINS_TEST:
                return collatedString.contains(searchCollatedString);
            default:
                throw new SwitchException("unknown testType: " + textTest.getTestType());
        }
    }

    public static CollatedStringTestUnit newInstance(TextTest textTest, RuleBasedCollator collator) {
        String searchCollatedString;
        switch (textTest.getTestType()) {
            case ConditionsConstants.EMPTY_TEST:
            case ConditionsConstants.NOT_EMPTY_TEST:
                searchCollatedString = "";
                break;
            default:
                searchCollatedString = CollationUnit.collate(textTest.getText(), collator);
        }
        return new CollatedStringTestUnit(textTest, searchCollatedString);
    }

}
