package cn.report.excel.easyexcel.api.converters.date;

import java.text.ParseException;
import java.util.Date;

import cn.report.excel.easyexcel.api.converters.Converter;
import cn.report.excel.easyexcel.api.enums.CellDataTypeEnum;
import cn.report.excel.easyexcel.api.metadata.GlobalConfiguration;
import cn.report.excel.easyexcel.api.metadata.data.ReadCellData;
import cn.report.excel.easyexcel.api.metadata.data.WriteCellData;
import cn.report.excel.easyexcel.api.metadata.property.ExcelContentProperty;
import cn.report.excel.easyexcel.api.util.DateUtils;

/**
 * Date and string converter
 *
 * @author Jiaju Zhuang
 */
public class DateStringConverter implements Converter<Date> {
    @Override
    public Class<?> supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
        GlobalConfiguration globalConfiguration) throws ParseException {
        if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
            return DateUtils.parseDate(cellData.getStringValue(), null);
        } else {
            return DateUtils.parseDate(cellData.getStringValue(),
                contentProperty.getDateTimeFormatProperty().getFormat());
        }
    }

    @Override
    public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty,
        GlobalConfiguration globalConfiguration) {
        if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
            return new WriteCellData<>(DateUtils.format(value, null));
        } else {
            return new WriteCellData<>(DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat()));
        }
    }
}
