/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.seatunnel.transform.coladd;

import com.google.auto.service.AutoService;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.seatunnel.api.configuration.ReadonlyConfig;
import org.apache.seatunnel.api.configuration.util.ConfigValidator;
import org.apache.seatunnel.api.table.catalog.CatalogTable;
import org.apache.seatunnel.api.table.catalog.Column;
import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
import org.apache.seatunnel.api.table.type.*;
import org.apache.seatunnel.api.transform.SeaTunnelTransform;
import org.apache.seatunnel.shade.com.typesafe.config.Config;
import org.apache.seatunnel.transform.common.MultipleFieldOutputTransform;
import org.apache.seatunnel.transform.common.SeaTunnelRowAccessor;
import org.apache.seatunnel.transform.utils.NumberUtil;
import org.apache.seatunnel.transform.utils.StringAssembler;
import scala.annotation.meta.field;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@AutoService(SeaTunnelTransform.class)
@NoArgsConstructor
public class ColAddTransform extends MultipleFieldOutputTransform {
    public static String PLUGIN_NAME = "ColAdd";
    private ColAddTransformConfig config;

    private List<String> fieldNames = new ArrayList<>();
    private List<SeaTunnelDataType> fieldTypes = new ArrayList<>();

    private static final ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");

    public ColAddTransform(
            @NonNull ColAddTransformConfig config, @NonNull CatalogTable catalogTable) {
        super(catalogTable);
        this.config = config;
    }

    @Override
    public String getPluginName() {
        return PLUGIN_NAME;
    }

    @Override
    protected void setConfig(Config pluginConfig) {
        ConfigValidator.of(ReadonlyConfig.fromConfig(pluginConfig))
                .validate(new ColAddTransformFactory().optionRule());
        config = ColAddTransformConfig.of(ReadonlyConfig.fromConfig(pluginConfig));
    }

    @Override
    protected void setInputRowType(SeaTunnelRowType inputRowType) {
    }

    @Override
    protected String[] getOutputFieldNames() {
        return fieldNames.toArray(new String[0]);
    }

    @Override
    protected SeaTunnelDataType[] getOutputFieldDataTypes() {
        return fieldTypes.toArray(new SeaTunnelDataType[0]);
    }

    @Override
    protected Column[] getOutputColumns() {
        Column[] columns = new Column[fieldNames.size()];
        for (int i = 0; i < fieldNames.size(); i++) {
            columns[i] =
                    PhysicalColumn.of(fieldNames.get(i), fieldTypes.get(i), 200, true, "", "");
        }
        return columns;
    }


    @Override
    protected SeaTunnelRowType transformRowType(SeaTunnelRowType inputRowType) {
        List<ColAddEntity> colAddEntityList = config.getColAddEntityList();
        List<String> rowFieldNames= Arrays.asList(inputRowType.getFieldNames());
        List<SeaTunnelDataType<?>> seaTunnelDataTypes = Arrays.asList(inputRowType.getFieldTypes());
        fieldNames.addAll(rowFieldNames);
        fieldTypes.addAll(seaTunnelDataTypes);
        colAddEntityList.forEach(col->{
            String field = col.getField();
            String fieldType = col.getFieldType();
            fieldNames.add(field);
            if ("INT".equalsIgnoreCase(fieldType)){
                fieldTypes.add(BasicType.INT_TYPE);
            }else if ("BIGINT".equalsIgnoreCase(fieldType)){
                fieldTypes.add(BasicType.LONG_TYPE);
            }else if ("FLOAT".equalsIgnoreCase(fieldType)){
                fieldTypes.add(BasicType.FLOAT_TYPE);
            }else if ("DOUBLE".equalsIgnoreCase(fieldType)){
                fieldTypes.add(BasicType.DOUBLE_TYPE);
            }else {
                fieldTypes.add(BasicType.STRING_TYPE);
            }
        });
        return new SeaTunnelRowType(fieldNames.toArray(new String[0]), fieldTypes.toArray(new SeaTunnelDataType[0]));
    }


    @Override
    protected SeaTunnelRow transformRow(SeaTunnelRow inputRow) {
        List<ColAddEntity> colAddEntityList = config.getColAddEntityList();
        Map<String, ColAddEntity> fieldIdMap = colAddEntityList.stream().collect(Collectors.toMap(ColAddEntity::getField, t -> t));
        Object[] fieldValues = new Object[fieldNames.size()];
        for (int i = 0; i < fieldNames.size(); i++) {
            String column = fieldNames.get(i);
            if (!fieldIdMap.containsKey(column)){
                fieldValues[i] = inputRow.getField(i);
            }else {
                ColAddEntity colAddEntity = fieldIdMap.get(column);
                String formula = StringAssembler.assemble(colAddEntity.getFormula(), key -> {
                    Object inputValue = inputRow.getField(fieldNames.indexOf(key));
                    String valueStr = _formatValue(inputValue);
                    //判断字段的值是否是数字，如果不是数字类型抛异常
                    if (colAddEntity.getAddMode() == AddMode.CALC && !NumberUtil.isNumber(valueStr)){
                        throw new UnsupportedOperationException(
                                "The column: " + column+"is not a number!");
                    }
                    return valueStr;
                });
                try {
                    fieldValues[i] = colAddEntity.getAddMode() == AddMode.CALC  ? jse.eval(formula) : formula;
                } catch (ScriptException e) {
                    e.printStackTrace();
                }
            }
        }
        return new SeaTunnelRow(fieldValues);
    }

    private String _formatValue(Object value) {
        Object _value = Optional.ofNullable(value).orElse(new Object());
        if(_value instanceof LocalDateTime) {
            return ((LocalDateTime)_value).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        return _value.toString();
    }

    @Override
    protected Object[] getOutputFieldValues(SeaTunnelRowAccessor inputRow) {
        return null;
    }


}
