/*
 *   Copyright 2013 Brian Rosenberger (Brutex Network)
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package net.brutex.xservices.ws.impl;

import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.jws.WebService;

import net.brutex.xservices.types.StringMatchType;
import net.brutex.xservices.types.StringReplaceType;
import net.brutex.xservices.types.StringSplitType;
import net.brutex.xservices.ws.StringService;
import net.brutex.xservices.ws.XServicesFault;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
import org.apache.commons.lang3.text.translate.NumericEntityEscaper;

/**
 * @author Brian Rosenberger, bru(at)brutex.de
 *
 */
@WebService(targetNamespace="http://ws.xservices.brutex.net", endpointInterface="net.brutex.xservices.ws.StringService", serviceName="StringService")
public class StringServiceImpl
  implements StringService
{
  public StringReplaceType replaceRegEx(String res, String search, String replace, String flags)
    throws XServicesFault
  {
    try
    {
      int allflags = getFlags(flags);
      Pattern pattern = Pattern.compile(search, allflags);
      Matcher matcher = pattern.matcher(res);
      int count = 0;
      while (matcher.find()) {
        count++;
      }
      if (flags.contains("g")) {
        return new StringReplaceType(matcher.replaceAll(replace), count);
      }
      if (count > 1)
        count = 1;
      return new StringReplaceType(matcher.replaceFirst(replace), 
        count);
    }
    catch (Exception e) {
      throw new XServicesFault(e);
    }
  }

  public StringMatchType matchRegEx(String res, String search, String flags)
    throws XServicesFault
  {
    int allflags = getFlags(flags);
    Pattern pattern = Pattern.compile(search, allflags);
    Matcher matcher = pattern.matcher(res);
    StringMatchType rm = new StringMatchType();
    
	for (int i=0; i <= matcher.groupCount(); i++) {
	    	while(matcher.find()) {
	    		rm.addStringMatch(matcher.start(i), matcher.end(i), "group-"+i, matcher.group(i));
	    	}
	    	matcher.reset();
	 }
    return rm;
  }

  public String encodeToXMLEntities(String res)
    throws XServicesFault
  {
    StringEscapeUtils fac = new StringEscapeUtils();
    StringEscapeUtils.ESCAPE_XML.with(new CharSequenceTranslator[] { NumericEntityEscaper.between(128, 2147483647) });
    return StringEscapeUtils.escapeXml(res);
  }
  
  public StringSplitType splitString(String paramString, String delimiter) throws XServicesFault {
		StringTokenizer tk = new StringTokenizer(paramString, delimiter);
		StringSplitType result = new StringSplitType();
		while(tk.hasMoreTokens()) {
			result.addStringMatch( tk.nextToken() );
		}
		return result;
	}
  
  @Override
	public String removeCRLF(String paramString) throws XServicesFault {
		String value = paramString.replaceAll("[\r\n]", "");
		return value;
	}

  private int getFlags(String flags) {
    int allflags = 0;
    if (flags.contains("i")) {
      allflags += 2;
    }
    if (flags.contains("m")) {
      allflags += 8;
    }
    if (flags.contains("u")) {
      allflags += 64;
    }
    if (flags.contains("s")) {
      allflags += 32;
    }
    if (flags.contains("d")) {
      allflags++;
    }
    if (flags.contains("x")) {
      allflags += 4;
    }
    return allflags;
  }
}
