package pl.qumak.xml;

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


public class DateAdapter {

    private static ThreadLocal<SimpleDateFormat> simpleDateFormat = new ThreadLocal<SimpleDateFormat>();
    private static ThreadLocal<SimpleDateFormat> datex2SimpleDateFormat = new ThreadLocal<SimpleDateFormat>();

    private static SimpleDateFormat getSimpleDateFormat(){
        if(simpleDateFormat.get() == null){
            simpleDateFormat.set(new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ssZ"));
        }
        return simpleDateFormat.get();
    }

    private static SimpleDateFormat getDatex2SimpleDateFormat(){
        if(datex2SimpleDateFormat.get() == null){
            datex2SimpleDateFormat.set(new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ss"));
        }
        return datex2SimpleDateFormat.get();
    }

    public static LocalDateTime unmarshal(String dateStr)  {
        if(dateStr == null) return null;
        try {
            Date date = getSimpleDateFormat().parse(dateStr);
            ToUTCDateConverter dateConverter = new ToUTCDateConverter();
            return dateConverter.convertToEntityAttribute(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String marshal(LocalDateTime dateObj) {
        ToUTCDateConverter dateConverter = new ToUTCDateConverter();
        Date data = dateConverter.convertToDatabaseColumn(dateObj);
        if (data == null) return null;
        return getDatex2SimpleDateFormat().format(data);
    }

        public static LocalDateTime datex2Unmarshal(String dateStr)  {
        if(dateStr == null) return null;
        try {
            Date date = getDatex2SimpleDateFormat().parse(dateStr);
            ToUTCDateConverter dateConverter = new ToUTCDateConverter();
            return dateConverter.convertToEntityAttribute(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String datex2Marshal(LocalDateTime dateObj) {
        ToUTCDateConverter dateConverter = new ToUTCDateConverter();
        Date data = dateConverter.convertToDatabaseColumn(dateObj);
        if(data == null) return null;
        return getDatex2SimpleDateFormat().format(data);
    }
}
