/*
 * 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.rowstack;

import com.google.auto.service.AutoService;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
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.catalog.TableSchema;
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.conversion.ValueType;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@AutoService(SeaTunnelTransform.class)
@NoArgsConstructor
public class RowStackTransform extends MultipleFieldOutputTransform {
    public static String PLUGIN_NAME = "RowStack";
    private RowStackTransformConfig config;
    private List<String> fieldNames;
    private List<SeaTunnelDataType> fieldTypes;
//    private SeaTunnelRowType inputRowType=null;
    private static SeaTunnelRowType outRowType=null;


    public RowStackTransform(
            @NonNull RowStackTransformConfig 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 RowStackTransformFactory().optionRule());
        config = RowStackTransformConfig.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) {
        if (outRowType == null){
            List<String> fieldList = config.getFieldList();
            List<String> fieldTypeList = config.getFieldTypeList();
            List<String> fieldNames = new ArrayList<>();
            List<SeaTunnelDataType> fieldsType = new ArrayList<>();
            fieldNames.addAll(fieldList);
            convert(fieldsType,fieldTypeList);
            outRowType = new SeaTunnelRowType(fieldNames.toArray(new String[0]), fieldsType.toArray(new SeaTunnelDataType[0]));
            this.fieldNames=fieldNames;
            this.fieldTypes=fieldsType;
        }
//        this.inputRowType=inputRowType;
        return outRowType;

    }


    @Override
    protected SeaTunnelRow transformRow(SeaTunnelRow inputRow) {
        List<RowStackEntity> list = config.getFieldConfigList();
        String tableId = inputRow.getTableId();
        Map<String,List<RowMap>> map = list.stream().collect(Collectors.toMap(RowStackEntity::getSourceTable,RowStackEntity::getList, (t1, t2) -> t1));
        List<RowMap> rowMapList = map.get(tableId);
        Map<String,String> filedMap = rowMapList.stream().collect(Collectors.toMap(RowMap::getMainColumn,RowMap::getColumn));
        List<String> fieldList = rowMapList.stream().map(RowMap::getColumn).collect(Collectors.toList());
        Object[] fieldValues = new Object[fieldNames.size()];
        for (int i = 0; i < fieldNames.size(); i++) {
            if (filedMap.containsKey(fieldNames.get(i))){
                int index = fieldList.indexOf(filedMap.get(fieldNames.get(i)));
                Object value = inputRow.getField(index);
                fieldValues[i]= value != null ? value.toString() : null;
            }else {
                fieldValues[i] = null;
            }
        }
        return new SeaTunnelRow(fieldValues);
    }


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


    public List<SeaTunnelDataType> convert(List<SeaTunnelDataType> list,List<String> fieldTypeList){
        for (String type :fieldTypeList ){
//            switch (type) {
//                case "INT":
//                    list.add(BasicType.INT_TYPE);
//                    continue;
//                case "TINYINT":
//                    list.add(BasicType.BYTE_TYPE);
//                case "SMALLINT":
//                    list.add(BasicType.SHORT_TYPE);
//                    continue;
//                case "DOUBLE":
//                    list.add(BasicType.DOUBLE_TYPE);
//                    continue;
//                case "DECIMAL":
//                    list.add(new DecimalType(30,10));
//                    continue;
//                case "LONG":
//                    list.add(BasicType.LONG_TYPE);
//                    continue;
//                case "FLOAT":
//                    list.add(BasicType.FLOAT_TYPE);
//                    continue;
//                case "BOOLEAN":
//                    list.add(BasicType.BOOLEAN_TYPE);
//                    continue;
//                case "DATE":
//                    list.add(LocalTimeType.LOCAL_DATE_TYPE);
//                    continue;
//                case "TIME":
//                    list.add(LocalTimeType.LOCAL_TIME_TYPE);
//                    continue;
//                case "TIMESTAMP":
//                    list.add(LocalTimeType.LOCAL_DATE_TIME_TYPE);
//                    continue;
//                default:
//                    list.add(BasicType.STRING_TYPE);
//                    continue;
//            }
            list.add(BasicType.STRING_TYPE);

        }
        return list;
    }


}
