package com.lingniu.ingest.protocol.jt1078.media;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetSocketAddress;

public final class Jt1078MediaStreamHandler extends SimpleChannelInboundHandler<Object> {

    private final Jt1078MediaArchiveService archiveService;
    private final Jt1078MalformedRtpEventPublisher malformedPublisher;

    public Jt1078MediaStreamHandler(Jt1078MediaArchiveService archiveService,
                                    Jt1078MalformedRtpEventPublisher malformedPublisher) {
        this.archiveService = archiveService;
        this.malformedPublisher = malformedPublisher;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof Jt1078RtpPacket packet) {
            archiveService.archive(packet, addr(ctx));
        } else if (msg instanceof Jt1078MalformedRtpPacket malformed) {
            malformedPublisher.publish(malformed);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    private static String addr(ChannelHandlerContext ctx) {
        if (ctx.channel().remoteAddress() instanceof InetSocketAddress i) {
            return i.getAddress().getHostAddress() + ":" + i.getPort();
        }
        return "unknown";
    }
}
