package org.apache.seatunnel.datasource.plugin.influxdb.client;

import org.apache.seatunnel.shade.com.google.common.collect.ImmutableMap;

import org.apache.seatunnel.api.table.catalog.DataTypeConvertException;
import org.apache.seatunnel.api.table.catalog.DataTypeConvertor;
import org.apache.seatunnel.api.table.type.BasicType;
import org.apache.seatunnel.api.table.type.LocalTimeType;
import org.apache.seatunnel.api.table.type.PrimitiveByteArrayType;
import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
import org.apache.seatunnel.common.exception.CommonErrorCode;
import org.apache.seatunnel.common.exception.SeaTunnelRuntimeException;

import com.google.auto.service.AutoService;

import java.util.Collections;
import java.util.Map;

import static org.apache.seatunnel.datasource.plugin.influxdb.client.InfluxdbType.NULL;
import static org.apache.seatunnel.shade.com.google.common.base.Preconditions.checkNotNull;

@AutoService(DataTypeConvertor.class)
public class InfluxdbDataTypeConvertor implements DataTypeConvertor<InfluxdbType> {

    public static final String PRECISION = "precision";
    public static final String SCALE = "scale";

    public static final Integer DEFAULT_PRECISION = 10;

    public static final Integer DEFAULT_SCALE = 0;

    @Override
    public SeaTunnelDataType<?> toSeaTunnelType(String connectorDataType) {
        checkNotNull(connectorDataType, "connectorDataType can not be null");
        InfluxdbType mysqlType = InfluxdbType.getByName(connectorDataType);
        Map<String, Object> dataTypeProperties;
        switch (mysqlType) {
            case BIGINT_UNSIGNED:
            case DECIMAL:
            case DECIMAL_UNSIGNED:
            case BIT:
                // parse precision and scale
                int left = connectorDataType.indexOf("(");
                int right = connectorDataType.indexOf(")");
                int precision = DEFAULT_PRECISION;
                int scale = DEFAULT_SCALE;
                if (left != -1 && right != -1) {
                    String[] precisionAndScale =
                            connectorDataType.substring(left + 1, right).split(",");
                    if (precisionAndScale.length == 2) {
                        precision = Integer.parseInt(precisionAndScale[0]);
                        scale = Integer.parseInt(precisionAndScale[1]);
                    } else if (precisionAndScale.length == 1) {
                        precision = Integer.parseInt(precisionAndScale[0]);
                    }
                }
                dataTypeProperties = ImmutableMap.of(PRECISION, precision, SCALE, scale);
                break;
            default:
                dataTypeProperties = Collections.emptyMap();
                break;
        }
        return toSeaTunnelType(mysqlType, dataTypeProperties);
    }

    @Override
    public SeaTunnelDataType<?> toSeaTunnelType(
            InfluxdbType influxdbType, Map<String, Object> dataTypeProperties)
            throws DataTypeConvertException {
        int precision;
        int scale;
        switch (influxdbType) {
            case NULL:
                return BasicType.VOID_TYPE;
            case BOOLEAN:
                return BasicType.BOOLEAN_TYPE;
            case BIT:
                precision = (Integer) dataTypeProperties.get(InfluxdbDataTypeConvertor.PRECISION);
                if (precision == 1) {
                    return BasicType.BOOLEAN_TYPE;
                } else {
                    return PrimitiveByteArrayType.INSTANCE;
                }
            case TINYINT:
                return BasicType.BYTE_TYPE;
            case TINYINT_UNSIGNED:
            case SMALLINT:
                return BasicType.SHORT_TYPE;
            case SMALLINT_UNSIGNED:
            case INT:
            case MEDIUMINT:
            case MEDIUMINT_UNSIGNED:
            case YEAR:
                return BasicType.INT_TYPE;
            case INT_UNSIGNED:
            case BIGINT:
                return BasicType.LONG_TYPE;
            case FLOAT:
            case FLOAT_UNSIGNED:
                return BasicType.FLOAT_TYPE;
            case DOUBLE:
            case DOUBLE_UNSIGNED:
                return BasicType.DOUBLE_TYPE;
            case TIME:
                return LocalTimeType.LOCAL_TIME_TYPE;
            case DATE:
                return LocalTimeType.LOCAL_DATE_TYPE;
            case TIMESTAMP:
            case DATETIME:
                return LocalTimeType.LOCAL_DATE_TIME_TYPE;
                // TODO: to confirm
            case CHAR:
            case VARCHAR:
            case TINYTEXT:
            case TEXT:
            case MEDIUMTEXT:
            case LONGTEXT:
            case JSON:
            case ENUM:
                return BasicType.STRING_TYPE;
            case BINARY:
            case VARBINARY:
            case TINYBLOB:
            case BLOB:
            case MEDIUMBLOB:
            case LONGBLOB:
            case GEOMETRY:
                return PrimitiveByteArrayType.INSTANCE;
            case BIGINT_UNSIGNED:
            case DECIMAL:
            case DECIMAL_UNSIGNED:
                return BasicType.DOUBLE_TYPE;
            default:
                throw DataTypeConvertException.convertToSeaTunnelDataTypeException(influxdbType);
        }
    }

    @Override
    public InfluxdbType toConnectorType(
            SeaTunnelDataType<?> seaTunnelDataType, Map<String, Object> map)
            throws DataTypeConvertException {
        switch (seaTunnelDataType.getSqlType()) {
            case ARRAY:
            case MAP:
            case ROW:
            case STRING:
                return InfluxdbType.VARCHAR;
            case BOOLEAN:
                return InfluxdbType.BOOLEAN;
            case TINYINT:
                return InfluxdbType.TINYINT;
            case SMALLINT:
                return InfluxdbType.SMALLINT;
            case INT:
                return InfluxdbType.INT;
            case BIGINT:
                return InfluxdbType.BIGINT;
            case FLOAT:
                return InfluxdbType.FLOAT;
            case DOUBLE:
                return InfluxdbType.DOUBLE;
            case DECIMAL:
                return InfluxdbType.DECIMAL;
            case NULL:
                return InfluxdbType.NULL;
            case BYTES:
                return InfluxdbType.BIT;
            case DATE:
                return InfluxdbType.DATE;
            case TIME:
                return InfluxdbType.DATETIME;
            case TIMESTAMP:
                return InfluxdbType.TIMESTAMP;
            default:
                throw new SeaTunnelRuntimeException(
                        CommonErrorCode.UNSUPPORTED_DATA_TYPE,
                        String.format(
                                "Doesn't support InfluxDB type '%s' yet",
                                seaTunnelDataType.getSqlType()));
        }
    }

    @Override
    public String getIdentity() {
        return "InfluxDB";
    }
}
