package com.ttstd.controller.webrtc;

import org.webrtc.DataChannel;
import org.webrtc.IceCandidate;
import org.webrtc.MediaStream;
import org.webrtc.PeerConnection;
import org.webrtc.RtpReceiver;

public class PeerObserver implements PeerConnection.Observer {

    private static final String TAG = "PeerObserver";

    private final PeerEventListener listener;

    public interface PeerEventListener {
        void onIceCandidate(IceCandidate candidate);
        void onIceConnectionChange(PeerConnection.IceConnectionState newState);
        void onDataChannel(DataChannel dataChannel);
        void onAddStream(MediaStream stream);
        void onRemoveStream(MediaStream stream);
        void onTrack(RtpReceiver receiver, MediaStream[] streams);
    }

    public PeerObserver(PeerEventListener listener) {
        this.listener = listener;
    }

    @Override
    public void onSignalingChange(PeerConnection.SignalingState newState) {
        android.util.Log.d(TAG, "Signaling state: " + newState);
    }

    @Override
    public void onIceConnectionChange(PeerConnection.IceConnectionState newState) {
        android.util.Log.d(TAG, "ICE connection state: " + newState);
        if (listener != null) listener.onIceConnectionChange(newState);
    }

    @Override
    public void onIceConnectionReceivingChange(boolean receiving) {}

    @Override
    public void onIceGatheringChange(PeerConnection.IceGatheringState newState) {
        android.util.Log.d(TAG, "ICE gathering state: " + newState);
    }

    @Override
    public void onIceCandidate(IceCandidate candidate) {
        if (listener != null) listener.onIceCandidate(candidate);
    }

    @Override
    public void onIceCandidatesRemoved(IceCandidate[] candidates) {}

    @Override
    public void onAddStream(MediaStream stream) {
        if (listener != null) listener.onAddStream(stream);
    }

    @Override
    public void onRemoveStream(MediaStream stream) {
        if (listener != null) listener.onRemoveStream(stream);
    }

    @Override
    public void onDataChannel(DataChannel dataChannel) {
        android.util.Log.d(TAG, "Data channel received: " + dataChannel.label());
        if (listener != null) listener.onDataChannel(dataChannel);
    }

    @Override
    public void onRenegotiationNeeded() {
        android.util.Log.d(TAG, "Renegotiation needed");
    }

    @Override
    public void onAddTrack(RtpReceiver receiver, MediaStream[] streams) {
        android.util.Log.d(TAG, "Track added: " + receiver.id());
        if (listener != null) listener.onTrack(receiver, streams);
    }
}
