/***********************************************************
 Copyright (C) 2004 VeriSign, Inc.

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-0107  USA

 http://www.verisign.com/nds/naming/namestore/techdocs.html
 ***********************************************************/
package com.verisign.epp.codec.change.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.verisign.epp.codec.gen.EPPEncodeException;
import com.verisign.epp.codec.gen.EPPUtil;

/**
 * Utility class to facilitate String processing
 * @author jcolosi
 */
public class TextUtil {

  static public Date decodeDate(String date) throws ParseException {
    SimpleDateFormat XML_DATE = new SimpleDateFormat("yyyy-MM-dd");
    return date != null ? XML_DATE.parse(date) : null;
  }

  static public String encodeDate(Date date) {
    SimpleDateFormat XML_DATE = new SimpleDateFormat("yyyy-MM-dd");
    return date != null ? XML_DATE.format(date) : null;
  }

  public static void encodeDate(Document aDocument, Element aRoot, Date aDate,
      String aNS, String aTagName) throws EPPEncodeException {
    EPPUtil.encodeString(aDocument, aRoot, encodeDate(aDate), aNS, aTagName);
  }

  static public Date normalize(Date date) {
    try {
      SimpleDateFormat XML_DATE = new SimpleDateFormat("yyyy-MM-dd");
      return date != null ? XML_DATE.parse(XML_DATE.format(date)) : null;
    } catch (ParseException x) {
      /**
       * LOGIC: There should never be a ParseException because we should
       * always be able to parse something that we just formatted. This
       * code will never be reached. I want to catch the ParseException
       * here so I don't have to handle a phantom Exception all the way up
       * the stack.
       */
      return null;
    }
  }

  static public String normalize(String value) {
    return value != null ? value.trim().replaceAll("\\s+", " ") : null;
  }

}
