package org.matrix.autotest.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;

/**
 * GrammarTable. 语法提示的数据库表结构
 *
 * @author Matrix <xhyrzldf@gmail.com>
 * @since 2022/3/25 at 11:06 AM
 * Suffering is the most powerful teacher of life.
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel("语法提示的数据库表结构")
public class GrammarTable {

    @ApiModelProperty("表名")
    private String tableName;
    @ApiModelProperty("表描述")
    private String tableDes;
    @ApiModelProperty("字段列表")
    private List<GrammarField> fields;

    public GrammarTable(String tableName, String tableDes) {
        this.tableName = tableName;
        this.tableDes = tableDes;
        this.fields = new ArrayList<>();
    }

    public List<GrammarTableField> tran2TableField(List<Map<String, Object>> originalMap) {
        return originalMap.stream()
                .map(m -> new GrammarTableField(m.get("tableName").toString(), m.get("tableDes").toString(), m.get("fieldName").toString(), m.get("fieldDes").toString(), m.get("fieldType").toString()))
                .collect(toList());
    }

    public List<GrammarTable> trans2Table(List<Map<String, Object>> originalMap) {
        List<GrammarTableField> tableFields = originalMap.stream()
                .map(m -> new GrammarTableField(m.get("tableName").toString(), m.get("tableDes").toString(), m.get("fieldName").toString(), m.get("fieldDes").toString(), m.get("fieldType").toString()))
                .collect(toList());

        List<GrammarTable> grammarTables = new ArrayList<>();

        tableFields.stream()
                .collect(groupingBy(GrammarTableField::getTableName))
                .forEach((k, v) -> {
                    GrammarTable table = new GrammarTable(v.get(0).getTableName(), v.get(0).getTableDes());
                    for (GrammarTableField field : v) {
                        table.getFields().add(field.extractField());
                    }
                    grammarTables.add(table);
                });

        return grammarTables;
    }
}
