package com.wdkl.ncs.janus.rtc.observer;

import android.util.Log;


import com.wdkl.ncs.janus.rtc.Peer;

import org.webrtc.SdpObserver;
import org.webrtc.SessionDescription;

public class OfferSdpObserver implements SdpObserver {
    private final static String TAG = OfferSdpObserver.class.getSimpleName();

    Peer peer;
    CreateOfferCallback callback;

    public OfferSdpObserver(Peer peer, CreateOfferCallback callback){
        this.peer = peer;
        this.callback = callback;
    }

    @Override
    public void onCreateSuccess(SessionDescription originalSdp) {
        Log.d(TAG, "createOffer sdp创建成功       " + originalSdp.type);
        final SessionDescription sdp = new SessionDescription(originalSdp.type, originalSdp.description);
        peer.setLocalSdp(sdp);
        peer.getPeerConnection().setLocalDescription(new SdpObserver() {
            @Override
            public void onCreateSuccess(SessionDescription sessionDescription) {
                Log.d(TAG, "setLocalDescription sdp创建成功       " + sessionDescription.type);
            }

            @Override
            public void onSetSuccess() {
                Log.d(TAG, "setLocalDescription onSetSuccess");
                if (peer.getPeerConnection().getRemoteDescription()==null){
                    //发出offer
                    if (callback != null) {
                        callback.onCreateOfferSuccess(sdp);
                    }
                } else {
                    Log.d(TAG, "Remote SDP set succesfully");
                    peer.drainCandidates();
                }
            }

            @Override
            public void onCreateFailure(String s) {
                Log.d(TAG, "setLocalDescription onCreateFailure   " + s);
            }

            @Override
            public void onSetFailure(String s) {
                Log.d(TAG, "setLocalDescription onSetFailure   " + s);
            }
        },sdp);
    }

    @Override
    public void onSetSuccess() {
        Log.d(TAG, "createOffer onSetSuccess");
    }

    @Override
    public void onCreateFailure(String s) {
        Log.d(TAG, "createOffer onCreateFailure " + s);
        if (callback != null) {
            callback.onCreateFailed(s);
        }
    }

    @Override
    public void onSetFailure(String s) {
        Log.d(TAG, "createOffer onSetFailure " + s);
        if (callback != null) {
            callback.onCreateFailed(s);
        }
    }
}
