package com.inkasso.config.convert;

import java.text.*;
import java.util.Date;
import java.util.TimeZone;

public class DateConverter extends DateFormat {

  private static final long serialVersionUID = 1L;
  private DateFormat dateFormat;
  private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  private SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");

  public DateConverter(DateFormat dateFormat) {
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
    this.dateFormat = dateFormat;
  }

  @Override
  public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {

    String str = simpleDateFormat.format(date);
//        if(str.contains("00:00:00")) {
//            return new StringBuffer(simpleDateFormat1.format(date));
//        }else {
//           return new StringBuffer(str);
//        }
    return new StringBuffer(str);
    // return dateFormat.format(date, toAppendTo, fieldPosition);
  }

  @Override
  public Date parse(String source, ParsePosition pos) {

    Date date = null;

    try {

      if (source.length() > 10) {
        date = simpleDateFormat.parse(source, pos);
      } else {
        date = simpleDateFormat1.parse(source, pos);
      }
    } catch (Exception e) {

      date = dateFormat.parse(source, pos);
    }

    return date;
  }

  @Override
  public Date parse(String source) throws ParseException {

    Date date = null;

    try {

      if (source.length() > 10) {
        date = simpleDateFormat.parse(source);
      } else {
        date = simpleDateFormat1.parse(source);
      }

    } catch (Exception e) {

      date = dateFormat.parse(source);
    }

    return date;
  }

  @Override
  public Object clone() {
    Object format = dateFormat.clone();
    return new DateConverter((DateFormat) format);
  }
}

