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.List;

public class OrdinaryRegexNode extends BaseRegexNode {

    private RegexNode proxyRegexNode;

    public OrdinaryRegexNode(String expression) throws RegexpIllegalException, TypeNotMatchException {
        super(expression);
    }

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

    @Override
    protected void init(String expression, List<String> expressionFragments)
            throws RegexpIllegalException, TypeNotMatchException {
        if (expressionFragments.size() == 0) {
            return;
        }
        RegexNode[] regexNodes = new RegexNode[]{
                new OptionalRegexNode(expressionFragments, false),
                new SingleRegexNode(expressionFragments, false),
                new RepeatRegexNode(expressionFragments, false),
                new LinkRegexNode(expressionFragments, false)
        };
        for (RegexNode regexNode : regexNodes) {
            if (regexNode.test()) {
                proxyRegexNode = regexNode;
                proxyRegexNode.init();
                break;
            }
        }
    }

    @Override
    protected String random(String expression, List<String> expressionFragments)
            throws UninitializedException, RegexpIllegalException {
        if (proxyRegexNode == null) {
            return "";
        }
        return proxyRegexNode.random();
    }

}
