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

import com.qmth.boot.tools.excel.convertor.ValueConvertor;
import com.qmth.boot.tools.excel.model.FieldParam;
import org.apache.poi.ss.usermodel.Cell;

public class BooleanConvertor implements ValueConvertor<Boolean> {

    public static final BooleanConvertor instance = new BooleanConvertor();

    public static final String[] TRUE_TEXT = { "是", "yes", "true" };

    public static final String[] FALSE_TEXT = { "否", "no", "false" };

    @Override
    public Boolean parse(String value, FieldParam param) throws Exception {
        if (value != null) {
            if (match(value, TRUE_TEXT)) {
                return true;
            } else if (match(value, FALSE_TEXT)) {
                return false;
            }
        }
        return null;
    }

    @Override
    public void format(Boolean object, FieldParam param, Cell cell) throws Exception {
        if (object) {
            cell.setCellValue(TRUE_TEXT[0]);
        } else {
            cell.setCellValue(FALSE_TEXT[0]);
        }
    }

    private boolean match(String value, String[] texts) {
        for (String text : texts) {
            if (text.equalsIgnoreCase(value)) {
                return true;
            }
        }
        return false;
    }
}
