package com.jy.framework.mybatis.join;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.support.LambdaMeta;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import lombok.Getter;
import org.apache.ibatis.reflection.property.PropertyNamer;

@Getter(lombok.AccessLevel.PROTECTED)
public class Table<T> extends AbstractTable {

    public final QueryColumns all = new QueryColumns();

    private final String alias;
    private final String name;

    protected Table(Class<T> entityClass) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
        String tableName = tableInfo.getTableName();

        this.alias = tableName;
        this.name = tableName;
    }

    protected Table(Class<T> entityClass, String alias) {
        Assert.notBlank(alias, "table alias must not be blank");

        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
        String tableName = tableInfo.getTableName();

        this.alias = alias;
        this.name = tableName;
    }

    public QueryColumn field(SFunction<T, ?> function) {
        LambdaMeta meta = LambdaUtils.extract(function);
        String field = StrUtil.toUnderlineCase(PropertyNamer.methodToProperty(meta.getImplMethodName()));
        QueryColumn queryColumn = new QueryColumn(alias, field);
        all.add(queryColumn);
        return queryColumn;
    }

    @Override
    protected String format() {
        return alias.equals(name) ? alias : name + StringPool.SPACE + alias;
    }

}
