package cn.axzo.msg.center.service.pending.card.domain;

import cn.axzo.basics.common.exception.ServiceException;
import cn.axzo.msg.center.service.ButtonV3;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author yanglin
 */
@Getter
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class CardButtonStates {

    private final List<CardButtonState> states;

    public static CardButtonStates create(List<CardButtonState> buttonStates) {
        return new CardButtonStates(new ArrayList<>(
                buttonStates == null ? Collections.emptyList(): buttonStates));
    }

    public void setActionPerformed(ButtonV3 button) {
        ensureNoButtonActionPerformed();
        states.removeIf(s -> s.getButtonCode().equals(button.getCode()));
        CardButtonState state = new CardButtonState();
        state.setButtonCode(button.getCode());
        state.setIsActionPerformed(true);
        states.add(state);
    }

    private void ensureNoButtonActionPerformed() {
        boolean noActionPerformedButton = states.stream().noneMatch(CardButtonState::determineIsActionPerformed);
        if (!noActionPerformedButton)
            throw new ServiceException("无法设置多个按钮失效, 是否更改过配置?");
    }

    public boolean isButtonActionPerformed(ButtonV3 button) {
        return states.stream()
                .anyMatch(state -> {
                    boolean isTheButton = state.getButtonCode().equals(button.getCode());
                    boolean actionPerformed = state.determineIsActionPerformed();
                    return isTheButton && actionPerformed;
                });
    }

}