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.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeConvertor implements ValueConvertor<LocalDateTime> {

    public static final LocalDateTimeConvertor instance = new LocalDateTimeConvertor();

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

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