package com.sunyard.ssp.utils.regexp.model;

import com.sunyard.ssp.utils.regexp.exception.RegexpIllegalException;
import com.sunyard.ssp.utils.regexp.exception.TypeNotMatchException;
import com.sunyard.ssp.utils.regexp.exception.UninitializedException;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class OptionalRegexNode extends BaseRegexNode {

    private List<RegexNode> children;

    protected OptionalRegexNode(List<String> expressionFragments) throws RegexpIllegalException, TypeNotMatchException {
        super(expressionFragments);
    }

    protected OptionalRegexNode(List<String> expressionFragments, boolean initialize)
            throws RegexpIllegalException, TypeNotMatchException {
        super(expressionFragments, initialize);
    }

    @Override
    protected boolean test(String expression, List<String> expressionFragments) {
        for (String fragment : expressionFragments) {
            if ("|".equals(fragment)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void init(String expression, List<String> expressionFragments)
            throws RegexpIllegalException, TypeNotMatchException {
        children = new ArrayList<>();
        List<String> subFragments = new ArrayList<>();
        for (String fragment : expressionFragments) {
            if ("|".equals(fragment)) {
                children.add(new OrdinaryRegexNode(subFragments));
                subFragments = new ArrayList<>();
                continue;
            }
            subFragments.add(fragment);
        }
        children.add(new OrdinaryRegexNode(subFragments));
    }

    @Override
    protected String random(String expression, List<String> expressionFragments)
            throws UninitializedException, RegexpIllegalException {
        return children.get(new Random().nextInt(children.size())).random();
    }
}
