/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package textkeymatcher.service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import textkeymatcher.entity.DefaultColumns;
import textkeymatcher.entity.Columns;

/**
 *
 * @author seraphy
 */
public class RegularExpColumnSplitter implements ColumnSplitter {

    private Pattern pat;
    
    public RegularExpColumnSplitter(String strPattern) {
        if (strPattern == null) {
            throw new IllegalArgumentException();
        }
        pat = Pattern.compile(strPattern);
    }
    
    @Override
    public Columns splitColumns(String line) {
        String[] cols = null;

        if (StringUtils.isNotEmpty(line)) {
            Matcher mat = pat.matcher(line);
            if (mat.matches()) {
                int mx = mat.groupCount();
                cols = new String[mx];
                for (int idx = 0; idx < mx; idx++) {
                    cols[mx] = mat.group(idx + 1);
                }
            }
        }

        if (cols == null) {
            cols = new String[] {line};
        }
        
        return new DefaultColumns(cols);
    }
}
