package cn.skcks.docking.gb28181.wvp.sip.message.invite.response;

import cn.skcks.docking.gb28181.core.sip.listener.SipListener;
import cn.skcks.docking.gb28181.core.sip.message.processor.MessageProcessor;
import cn.skcks.docking.gb28181.core.sip.message.subscribe.GenericSubscribe;
import cn.skcks.docking.gb28181.wvp.sip.subscribe.SipSubscribe;
import gov.nist.javax.sip.message.SIPResponse;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.sip.ResponseEvent;
import javax.sip.message.Request;
import java.util.EventObject;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Component
public class InviteResponseProcessor implements MessageProcessor {
    private final SipListener sipListener;
    private final SipSubscribe subscribe;

    @PostConstruct
    @Override
    public void init() {
        sipListener.addResponseProcessor(Request.INVITE, this);
    }

    @Override
    public void process(EventObject eventObject) {
        ResponseEvent requestEvent = (ResponseEvent) eventObject;
        SIPResponse response = (SIPResponse) requestEvent.getResponse();
        String callId = response.getCallId().getCallId();
        String subscribeKey = GenericSubscribe.Helper.getKey(Request.INVITE, callId);
        log.info("收到 INVITE 响应, key {}", subscribeKey);
        Optional.ofNullable(subscribe.getInviteSubscribe().getPublisher(subscribeKey))
                .ifPresent(publisher->publisher.submit(response));
    }
}
