package com.qmth.boot.tools.excel.convertor.impl;

import com.qmth.boot.tools.excel.constants.ExcelConstants;
import com.qmth.boot.tools.excel.convertor.ValueConvertor;
import com.qmth.boot.tools.excel.model.FieldParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;

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

public class DateConvertor implements ValueConvertor<Date> {

    public static final DateConvertor instance = new DateConvertor();

    @Override
    public Date parse(String value, FieldParam param) throws Exception {
        String pattern = param.getAnnotation().pattern();
        if (StringUtils.isBlank(pattern)) {
            pattern = ExcelConstants.DEFAULT_DATE_PATTERN;
        }
        return new SimpleDateFormat(pattern).parse(value);
    }

    @Override
    public void format(Date object, FieldParam param, Cell cell) throws Exception {
        String pattern = param.getAnnotation().pattern();
        if (StringUtils.isBlank(pattern)) {
            pattern = ExcelConstants.DEFAULT_DATE_PATTERN;
        }
        cell.setCellValue(new SimpleDateFormat(pattern).format(object));
    }
}
