/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You 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 poi.support;

import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class POIFormatterUtil {

	public static final String LINE_SEPARATOR = System
			.getProperty("line.separator");

	private POIFormatterUtil() {
	}

	/**
	 * printf formatter (support d,i,e,E,f,x,n only)
	 *
	 * @param s
	 * @param fmt
	 * @param parts
	 * @return s
	 */
	public static StringBuffer format(StringBuffer s, String fmt, Object[] parts) {
		Pattern pat = Pattern
				.compile("%[\\-+ #0]?[0-9\\.]*[hljztL]*[diuoxXeEfFgGaAcspn]");
		Matcher matcher = pat.matcher(fmt);
		int pi = 0;
		int previousEnd = 0;
		while (matcher.find()) {
			String src = matcher.group();
			s.append(fmt.substring(previousEnd, matcher.start()));
			String dest;
			char c = src.charAt(src.length() - 1);
			switch (c) {
			case 'd': {
				// example %d %5d %05d
				StringBuffer dfmt = new StringBuffer();
				int len = 0;
				boolean hasLength = false;
				if (src.charAt(1) == '0') {
					// %05d : zero padding
					hasLength = true;
					len = Integer.parseInt(src.substring(2, src.length() - 1));
					for (int i = 0; i < len; i++) {
						dfmt.append('0');
					}
				} else if (src.charAt(1) == 'd') {
					// %d
					dfmt.append('0');
				} else {
					// %5d : space padding
					hasLength = true;
					len = Integer.parseInt(src.substring(1, src.length() - 1));
					for (int i = 0; i < len; i++) {
						dfmt.append(' ');
					}
					dfmt.append('0');
				}
				DecimalFormat df = new DecimalFormat(dfmt.toString());
				dest = df.format((Long) parts[pi]);
				String dest2 = String.valueOf((Long) parts[pi]);
				if (hasLength && dest2.length() < len) {
					dest = dest.substring(dest.length() - len);
				} else {
					dest = dest2;
				}
				break;
			}
			case 'e':
			case 'E': {
				// example %e %.5e %1.5e %E %.5E %1.5E
				int dotIndex = src.indexOf('.');
				if (dotIndex < 0) {
					DecimalFormat df = new DecimalFormat("0.000000E00");
					dest = df.format((Double) parts[pi]);
				} else {
					StringBuffer dfmt = new StringBuffer("0.");
					int len = Integer.parseInt(src.substring(dotIndex + 1,
							src.length() - 1));
					for (int i = 0; i < len; i++) {
						dfmt.append('0');
					}
					dfmt.append("E00");
					DecimalFormat df = new DecimalFormat(dfmt.toString());
					dest = df.format((Double) parts[pi]);
				}
				int eIndex = dest.indexOf('E');
				if (eIndex >= 0 && !('-' == dest.charAt(eIndex + 1))) {
					dest = dest.substring(0, eIndex) + c + "+"
							+ dest.substring(eIndex + 1);
				}
				if (c == 'e') {
					dest = dest.replace('E', 'e');
				}
				break;
			}
			case 'f': {
				// example %f %.5f %1.5f
				int dotIndex = src.indexOf('.');
				if (dotIndex < 0) {
					DecimalFormat df = new DecimalFormat("0.000000");
					dest = df.format((Double) parts[pi]);
				} else {
					StringBuffer dfmt = new StringBuffer("0");
					int len = Integer.parseInt(src.substring(dotIndex + 1,
							src.length() - 1));
					if (len > 0) {
						dfmt.append('.');
					}
					for (int i = 0; i < len; i++) {
						dfmt.append('0');
					}
					DecimalFormat df = new DecimalFormat(dfmt.toString());
					dest = df.format((Double) parts[pi]);
				}
				break;
			}
			case 'x': {
				// example %x %2x %02x
				StringBuffer dfmt = new StringBuffer();
				int len = 0;
				boolean hasLength = false;
				if (src.charAt(1) == '0') {
					// %02x : zero padding
					hasLength = true;
					len = Integer.parseInt(src.substring(2, src.length() - 1));
					for (int i = 0; i < len; i++) {
						dfmt.append('0');
					}
				} else if (src.charAt(1) == 'x') {
					// %x
				} else {
					// %2x : space padding
					hasLength = true;
					len = Integer.parseInt(src.substring(1, src.length() - 1));
					for (int i = 0; i < len; i++) {
						dfmt.append(' ');
					}
				}
				String hex = Long.toHexString(((Long) parts[pi]).longValue());
				dest = dfmt.toString() + hex;
				if (hasLength && hex.length() < len) {
					dest = dest.substring(dest.length() - len);
				} else {
					dest = hex;
				}
				break;
			}
			case 'n': {
				// example %n
				// replace
				s.append(LINE_SEPARATOR);
				// next
				previousEnd = matcher.end();
				continue;
			}
			default:
				throw new IllegalArgumentException("Not supported:" + src);
			}
			// replace
			s.append(dest);
			// next
			previousEnd = matcher.end();
			pi++;
		}
		if (fmt.length() > previousEnd) {
			s.append(fmt.substring(previousEnd));
		}
		return s;
	}

}
