package cn.axzo.msg.center.api.custombutton;

import cn.axzo.msg.center.service.dto.ButtonRouterDTO;
import cn.axzo.msg.center.service.enums.RouterButtonSourceEnum;
import cn.axzo.msg.center.service.pending.response.PendingMessageResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.function.Function;

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

/**
 * @author yanglin
 */
@RequiredArgsConstructor
public class ProposedButtonFilter {

    public static void adjustProposedButtons(PendingMessageResponse response, boolean forPromoter) {
        response.setButtonRouters(filterProposedButtons(response, forPromoter));
    }

    public static List<ButtonRouterDTO> filterProposedButtons(PendingMessageResponse response, boolean forPromoter) {
        ProposedButtons buttons = response.getProposedButtons();
        Function<String, Boolean> isConfiguredProposedBtnFun = btnKey -> {
            if (buttons == null || CollectionUtils.isEmpty(buttons.getConfiguredButtonKeys()))
                return false;
            return buttons.getConfiguredButtonKeys().contains(btnKey);
        };
        Function<String, ProposedButton> findProposedBtnFun = btnKey -> {
            if (buttons == null || CollectionUtils.isEmpty(buttons.getProposedButtons()))
                return null;
            return buttons.getProposedButtons().stream()
                    .filter(i -> btnKey.equals(i.getButtonKey()))
                    .findFirst()
                    .orElse(null);
        };
        Function<ButtonRouterDTO, Boolean> syncBtnFun = btn -> {
            // 没有配置可见的自定义的按钮
            ProposedButton proposedBtn = findProposedBtnFun.apply(btn.getKey());
            if (proposedBtn == null || CollectionUtils.isEmpty(proposedBtn.getConfigs()))
                return false;
            return proposedBtn.getConfigs().stream()
                    .anyMatch(c -> forPromoter
                            ? c.isVisible(response.getBizFinalState())
                            : c.isVisible(response.getState()));
        };
        return response.getButtonRouters().stream()
                .filter(routerBtn -> {
                    ProposedButton proposedBtn = findProposedBtnFun.apply(routerBtn.getKey());
                    boolean isNormalCustomBtn = proposedBtn == null
                            && !isConfiguredProposedBtnFun.apply(routerBtn.getKey())
                            && routerBtn.getSource() == RouterButtonSourceEnum.CUSTOM;
                    return isNormalCustomBtn || syncBtnFun.apply(routerBtn);
                })
                .collect(toList());
    }

}