package cn.skcks.docking.gb28181.wvp.sip.subscribe;

import cn.skcks.docking.gb28181.core.sip.executor.DefaultSipExecutor;
import cn.skcks.docking.gb28181.core.sip.message.subscribe.GenericSubscribe;
import cn.skcks.docking.gb28181.core.sip.message.subscribe.GenericTimeoutSubscribe;
import cn.skcks.docking.gb28181.core.sip.message.subscribe.InviteSubscribe;
import cn.skcks.docking.gb28181.core.sip.message.subscribe.SipRequestSubscribe;
import gov.nist.javax.sip.message.SIPRequest;
import gov.nist.javax.sip.message.SIPResponse;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
@Data
@RequiredArgsConstructor
@Service
public class SipSubscribe {
    @Qualifier(DefaultSipExecutor.EXECUTOR_BEAN_NAME)
    private final Executor executor;
    private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
    private GenericSubscribe<SIPRequest> catalogSubscribe;
    private GenericSubscribe<SIPResponse> inviteSubscribe;
    private GenericSubscribe<SIPRequest> byeSubscribe;
    private GenericTimeoutSubscribe<SIPRequest> messageSubscribe;

    @PostConstruct
    private void init() {
        catalogSubscribe = new CatalogSubscribe(executor);
        inviteSubscribe = new InviteSubscribe(executor);
        byeSubscribe = new ByeSubscribe(executor);
        messageSubscribe = new SipRequestSubscribe(executor, scheduledExecutorService);
    }

    @PreDestroy
    private void destroy() {
        catalogSubscribe.close();
        inviteSubscribe.close();
        byeSubscribe.close();
        messageSubscribe.close();
    }
}
