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

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.*;
import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
import org.apache.seatunnel.api.table.type.SqlType;
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 java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@AutoService(SeaTunnelTransform.class)
@NoArgsConstructor
public class ConditionTransform extends MultipleFieldOutputTransform {
    public static String PLUGIN_NAME = "FieldCondition";
    private ConditionTransformConfig config;

    public ConditionTransform(
            @NonNull ConditionTransformConfig 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 ConditionTransformFactory().optionRule());
        config = ConditionTransformConfig.of(ReadonlyConfig.fromConfig(pluginConfig));
    }

    @Override
    protected SeaTunnelRowType transformRowType(SeaTunnelRowType inputRowType) {
        return inputRowType;
    }


    @Override
    protected SeaTunnelRow transformRow(SeaTunnelRow inputRow) {
        List<ConditionEntity> fieldCondition = config.getFieldCondition();
        String connectType = config.getConnectType();
        List<Boolean>flagList=new ArrayList<>();
        fieldCondition.forEach(x->{
            boolean flag=false;
            String valueStr = String.valueOf(inputRow.getField(inputRowType.indexOf(x.getField())));
            boolean number = NumberUtil.isNumber(valueStr);
            OperateType operateType = x.getOperateType();
            if (number){//判断是否是数字类型
                BigDecimal rowValue = new BigDecimal(valueStr);
                BigDecimal value = new BigDecimal(String.valueOf(x.getValue()));
                if (operateType == OperateType.GT){
                    if (rowValue.compareTo(value) > 0){
                        flag=true;
                    }
                }else if (operateType == OperateType.LT){
                    if (rowValue.compareTo(value) <0 ){
                        flag=true;
                    }
                }else if (operateType == OperateType.EQUAL){
                    if (rowValue.compareTo(value) == 0){
                        flag=true;
                    }
                }else if (operateType == OperateType.GTE){
                    if (rowValue.compareTo(value) >= 0){
                        flag=true;
                    }
                }else if (operateType == OperateType.LTE){
                    if (rowValue.compareTo(value) <= 0){
                        flag=true;
                    }
                }

            }else {
                //非数字，判断field的类型
                SeaTunnelDataType<?> fieldType = inputRowType.getFieldType(inputRowType.indexOf(x.getField()));
                SqlType sqlType = fieldType.getSqlType();
                if (sqlType == SqlType.STRING) {//字符串目前只支持相等操作
                    if (operateType == OperateType.EQUAL) {
                        if (valueStr.equals(String.valueOf(x.getValue()))) {
                            flag = true;
                        }
                    }
                }else if (sqlType == SqlType.DATE || sqlType == SqlType.TIME || sqlType == SqlType.TIMESTAMP){
                   String sdf="";
                    if (StringUtils.isBlank(x.getSdf())){
                        sdf="yyyy-MM-dd";
                    }else {
                        sdf=x.getSdf();
                    }
                    DateFormat format = new SimpleDateFormat(sdf);
                    String value = String.valueOf(x.getValue());
                    try {
                        Timestamp rowStamp = new Timestamp(format.parse(valueStr).getTime());
                        Timestamp valueStamp = new Timestamp(format.parse(value).getTime());
                        if (operateType == OperateType.GT){
                            if (rowStamp.getTime() > valueStamp.getTime()){
                                flag=true;
                            }
                        }else if (operateType == OperateType.LT){
                            if (rowStamp.getTime() < valueStamp.getTime()){
                                flag=true;
                            }
                        }else if (operateType == OperateType.EQUAL){
                            if (rowStamp.getTime() == valueStamp.getTime()){
                                flag=true;
                            }
                        }else if (operateType == OperateType.GTE){
                            if (rowStamp.getTime() >= valueStamp.getTime()){
                                flag=true;
                            }
                        }else if (operateType == OperateType.LTE){
                            if (rowStamp.getTime() <= valueStamp.getTime()){
                                flag=true;
                            }
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
            flagList.add(flag);
        });
        if ("AND".equals(connectType)){
            if (!flagList.contains(false)){
                SeaTunnelRow outputRow = new SeaTunnelRow(inputRow.getFields());
                outputRow.setRowKind(inputRow.getRowKind());
                outputRow.setTableId(inputRow.getTableId());
                return outputRow;
            }
        }else if("OR".equals(connectType)){
            if (flagList.contains(true)){
                SeaTunnelRow outputRow = new SeaTunnelRow(inputRow.getFields());
                outputRow.setRowKind(inputRow.getRowKind());
                outputRow.setTableId(inputRow.getTableId());
                return outputRow;
            }
        }
        return null;

    }

    @Override
    protected void setInputRowType(SeaTunnelRowType inputRowType) {

    }


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

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

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

    @Override
    protected TableSchema transformTableSchema() {
        return null;
    }

    @Override
    protected TableIdentifier transformTableIdentifier() {
        return inputCatalogTable.getTableId().copy();
    }

    @Override
    protected Column[] getOutputColumns() {
        return new Column[0];
    }
}
