package com.zzwtec.third.config.beetl;

import com.zzwtec.third.utils.TimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.Context;
import org.beetl.core.Function;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * create by Jomchen on 2018/11/29
 */
public class LongTimeFormat implements Function {
    private Map<String, DateTimeFormatter> formatterMap = new ConcurrentHashMap<>();

    @Override
    public Object call(Object[] var1, Context var2) {
        if (var1 == null || var1.length!=2) {
            return null;
        }
        if (!Long.class.isAssignableFrom(var1[0].getClass())) {
            throw new RuntimeException("format failed, expectedClass:" + Long.class
                    + " actualClass:" + var1[0].getClass());
        }
        if (!String.class.isAssignableFrom(var1[1].getClass())) {
            throw new RuntimeException("format failed, expectedClass:" + String.class
                    + " actualClass:" + var1[1].getClass());
        }
        LocalDateTime localDateTime = TimeUtil.long2LocalDateTime((Long)var1[0]);
        DateTimeFormatter dateTimeFormatter = genDateTimeFormatter((String)var1[1]);
        return localDateTime.format(dateTimeFormatter);
    }

    private DateTimeFormatter genDateTimeFormatter(String pattern) {
        if (StringUtils.isBlank(pattern)) {
            return DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        }

        DateTimeFormatter formatter = formatterMap.get(pattern);
        if (formatter != null) {
            return formatter;
        }
        formatter = DateTimeFormatter.ofPattern(pattern);
        formatterMap.put(pattern, formatter);
        return formatter;
    }

}
