package com.pictc.converts.date;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import com.pictc.converts.ConvertException;
import com.pictc.converts.TypeHandler;
import com.pictc.utils.ClassUtils;
import com.pictc.utils.DateUtils;
import com.pictc.utils.StringUtils;


public class TimestampHandler implements TypeHandler<Timestamp> {

    private Class<?>[] converts = new Class<?>[] { Timestamp.class };


    @Override
    public boolean isType(Class<?> type) {
        return Timestamp.class.equals(type);
    }


    @Override
    public Class<?>[] getConverts() {
        return converts;
    }


    @Override
    public Object convert(Timestamp value) {
        if (value == null) {
            return null;
        }
        String str = value.toString();
        if (str.contains(".")) {
            str = str.split("\\.")[0];
        }
        return str;
    }


    @Override
    public Timestamp valueToObject(Object val) {
        if (val == null) {
            return null;
        }
        Class<?> vcs = val.getClass();
        if (isType(vcs)) {
            return Timestamp.class.cast(val);
        } else if (val instanceof String) {
            String str = (String) val;
            if (str.matches("^\\d+$")) {
                return new Timestamp(Long.valueOf(str));
            }else if(str.matches("^.*T.*\\+.*$")) {
            	LocalDateTime date = LocalDateTime.parse(str,DateTimeFormatter.ISO_OFFSET_DATE_TIME);
            	return DateUtils.toTimestamp(date);
            } else if (StringUtils.isEmpty(str)) {
                return null;
            } else {
            	throw new ConvertException(vcs, val, Timestamp.class);
            }
        }else if(ClassUtils.isDate(vcs)) {
        	return new Timestamp(((Date)val).getTime());
        }else if(Long.class.equals(vcs) || long.class.equals(vcs)) {
        	 return new Timestamp(Long.class.cast(val));
        }else if(LocalDateTime.class.equals(vcs)){
       	 return DateUtils.toTimestamp(LocalDateTime.class.cast(val));
        } else {
        	throw new ConvertException(vcs, val, Timestamp.class);
        }
    }

}
