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.Arrays;
import java.util.Collections;
import java.util.List;

public class LinkRegexNode extends BaseRegexNode {

    private List<RegexNode> children;

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

    protected LinkRegexNode(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 false;
            }
        }
        return true;
    }

    @Override
    protected void init(String expression, List<String> expressionFragments)
            throws RegexpIllegalException, TypeNotMatchException {
        children = new ArrayList<>();
        for (int i = 0; i < expressionFragments.size(); i++) {
            RegexNode regexNode;
            if (i + 1 < expressionFragments.size()) {
                regexNode = new RepeatRegexNode(
                        Arrays.asList(expressionFragments.get(i), expressionFragments.get(i + 1)),
                        false);
                if (regexNode.test()) {
                    regexNode.init();
                    children.add(regexNode);
                    i++;
                    continue;
                }
            }
            regexNode = new SingleRegexNode(Collections.singletonList(expressionFragments.get(i)));
            children.add(regexNode);
        }
    }

    @Override
    protected String random(String expression, List<String> expressionFragments)
            throws RegexpIllegalException, UninitializedException {
        StringBuilder value = new StringBuilder();
        for (RegexNode regexNode : children) {
            value.append(regexNode.random());
        }
        return value.toString();
    }
}
