package com.liangjian.dataplatform.member.entity.vo.tagrules;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.List;

/**
 * @Author: 黄子奇
 * @Date: 2019/9/7 16:22
 */
@ApiModel("带层级的逻辑树")
public class BracketsLogicNode implements LogicNode {

    @ApiModelProperty(value = "逻辑类型", notes = "And, Or")
    private LogicType type;

    @ApiModelProperty("第一个二元操作")
    private BinOperation node;

    @ApiModelProperty(value = "剩下的逻辑节点", notes = "可以也是层级关系")
    private List<LogicNode> extNodes;

    public BracketsLogicNode() {
    }

    public BracketsLogicNode(LogicType type, BinOperation node, List<LogicNode> extNodes) {
        this.type = type;
        this.node = node;
        this.extNodes = extNodes;
    }

    @Override
    public LogicType getLogicType() {
        return this.type;
    }

    @Override
    public BinOperation getBinOperation() {
        return this.node;
    }

    @Override
    public boolean hasExtNodes() {
        return this.extNodes != null && !this.extNodes.isEmpty();
    }

    @Override
    public String toSql(SqlContext context) {
        if(hasExtNodes()){
            String sql = node.toSql(context) + " " +
                    extNodes.stream().map(i -> i.toSql(context)).reduce((i,j) -> i+" "+j).orElse("");
            LogicType logicType = type;
            if(this.type == LogicType.ANDNEW){
                logicType = LogicType.AND;
            } else if(this.type == LogicType.ORNEW) {
                logicType = LogicType.OR;
            }
            return String.format(" %s (%s)", logicType.toString(), sql);
        } else {
            LogicType logicType = type;
            if(this.type == LogicType.ANDNEW){
                logicType = LogicType.AND;
            } else if(this.type == LogicType.ORNEW) {
                logicType = LogicType.OR;
            }
            return logicType.toString() + " " + node.toSql(context);
        }
    }

    public static BracketsLogicNode AndNew(BinOperation node, List<LogicNode> extNodes) {
        return new BracketsLogicNode(LogicType.ANDNEW,node, extNodes);
    }

    public static BracketsLogicNode OrNew(BinOperation node, List<LogicNode> extNodes) {
        return new BracketsLogicNode(LogicType.ORNEW, node, extNodes);
    }

    public LogicType getType() {
        return type;
    }

    public void setType(LogicType type) {
        this.type = type;
    }

    public BinOperation getNode() {
        return node;
    }

    public void setNode(BinOperation node) {
        this.node = node;
    }

    @Override
    public List<LogicNode> getExtNodes() {
        return extNodes;
    }

    public void setExtNodes(List<LogicNode> extNodes) {
        this.extNodes = extNodes;
    }
}
