package com.rdiot.yx485;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zcolin.frame.app.FramePathConst;
import com.zcolin.frame.imageloader.ImageLoaderUtils;
import com.zcolin.frame.permission.PermissionHelper;
import com.zcolin.frame.permission.PermissionsResultAction;
import com.zcolin.frame.util.ActivityUtil;
import com.zcolin.frame.util.SystemIntentUtil;

import org.webrtc.DataChannel;
import org.webrtc.DefaultVideoDecoderFactory;
import org.webrtc.DefaultVideoEncoderFactory;
import org.webrtc.EglBase;
import org.webrtc.IceCandidate;
import org.webrtc.MediaConstraints;
import org.webrtc.MediaStream;
import org.webrtc.MediaStreamTrack;
import org.webrtc.PeerConnection;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.RtpReceiver;
import org.webrtc.RtpTransceiver;
import org.webrtc.SdpObserver;
import org.webrtc.SessionDescription;
import org.webrtc.SurfaceViewRenderer;

import java.util.ArrayList;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    private LinearLayout      llContent;
    private ImageView         imageView;
    private ArrayList<Button> listButton = new ArrayList<>();
    PeerConnection peerConnection;
    SdpObserver sdpObserver;
    SurfaceViewRenderer surfaceViewRenderer;
    TextView dianji;
    String sdp="v=0\\r\\no=- 1769570631059020219 2 IN IP4 192.168.200.215\\r\\ns=-\\r\\nt=0 0\\r\\na=group:BUNDLE 0 1\\r\\na=msid-semantic: WMS\\r\\na=ice-lite\\r\\nm=video 7004 UDP/TLS/RTP/SAVPF 123 119\\r\\nc=IN IP4 192.168.200.215\\r\\na=rtcp:7004 IN IP4 192.168.200.215\\r\\na=ice-ufrag:wKjI1xtcG1w=_505\\r\\na=ice-pwd:P2kplY7nYgZfKBNaSuB8HLuy\\r\\na=ice-options:trickle\\r\\na=fingerprint:sha-256 5D:43:0F:2C:BD:82:BB:C5:B4:77:42:D3:8C:2B:D5:1A:32:59:39:1D:78:7A:BB:88:E2:EF:2A:60:37:AD:6E:A3\\r\\na=setup:passive\\r\\na=mid:0\\r\\na=ice-lite\\r\\na=extmap:1 urn:ietf:params:rtp-hdrext:toffset\\r\\na=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\\r\\na=extmap:4 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\\r\\na=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay\\r\\na=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type\\r\\na=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing\\r\\na=extmap:8 http://www.webrtc.org/experiments/rtp-hdrext/color-space\\r\\na=extmap:10 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\\r\\na=extmap:11 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\\r\\na=sendonly\\r\\na=rtcp-mux\\r\\na=rtpmap:123 H264/90000\\r\\na=rtcp-fb:123 ccm fir\\r\\na=rtcp-fb:123 goog-remb\\r\\na=rtcp-fb:123 nack\\r\\na=rtcp-fb:123 nack pli\\r\\na=rtcp-fb:123 transport-cc\\r\\na=fmtp:123 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=64001f\\r\\na=rtpmap:119 rtx/90000\\r\\na=fmtp:119 apt=123\\r\\na=msid:zlmediakit-mslabel zlmediakit-label\\r\\na=ssrc:1 cname:zlmediakit-rtp\\r\\na=ssrc:1 msid:zlmediakit-mslabel zlmediakit-label\\r\\na=ssrc:1 mslabel:zlmediakit-mslabel\\r\\na=ssrc:1 label:zlmediakit-label\\r\\na=ssrc:3 cname:zlmediakit-rtp\\r\\na=ssrc:3 msid:zlmediakit-mslabel zlmediakit-label\\r\\na=ssrc:3 mslabel:zlmediakit-mslabel\\r\\na=ssrc:3 label:zlmediakit-label\\r\\na=ssrc-group:FID 1 3\\r\\na=candidate:udpcandidate 1 udp 110 192.168.200.215 7004 typ host\\r\\na=candidate:tcpcandidate 1 tcp 105 192.168.200.215 7004 typ host tcptype passive\\r\\nm=audio 7004 UDP/TLS/RTP/SAVPF 111\\r\\nc=IN IP4 192.168.200.215\\r\\na=rtcp:7004 IN IP4 192.168.200.215\\r\\na=ice-ufrag:wKjI1xtcG1w=_505\\r\\na=ice-pwd:P2kplY7nYgZfKBNaSuB8HLuy\\r\\na=ice-options:trickle\\r\\na=fingerprint:sha-256 5D:43:0F:2C:BD:82:BB:C5:B4:77:42:D3:8C:2B:D5:1A:32:59:39:1D:78:7A:BB:88:E2:EF:2A:60:37:AD:6E:A3\\r\\na=setup:passive\\r\\na=mid:1\\r\\na=ice-lite\\r\\na=extmap:14 urn:ietf:params:rtp-hdrext:ssrc-audio-level\\r\\na=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\\r\\na=extmap:4 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\\r\\na=inactive\\r\\na=rtcp-mux\\r\\na=rtpmap:111 opus/48000/2\\r\\na=rtcp-fb:111 transport-cc\\r\\na=fmtp:111 minptime=10;useinbandfec=1\\r\\na=msid:zlmediakit-mslabel zlmediakit-label\\r\\na=ssrc:2 cname:zlmediakit-rtp\\r\\na=ssrc:2 msid:zlmediakit-mslabel zlmediakit-label\\r\\na=ssrc:2 mslabel:zlmediakit-mslabel\\r\\na=ssrc:2 label:zlmediakit-label\\r\\na=candidate:udpcandidate 1 udp 110 192.168.200.215 7004 typ host\\r\\na=candidate:tcpcandidate 1 tcp 105 192.168.200.215 7004 typ host tcptype passive\\r\\n";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        //setRemoteDescription(sdp);
        inintdate();
    }

    private void init() {
        surfaceViewRenderer =findViewById(R.id.activity_main_svr_video);
        dianji =findViewById(R.id.dianji);
        llContent = getView(R.id.ll_content);
        imageView = getView(R.id.imageview);
        listButton.add(addButton("Http演示"));
        listButton.add(addButton("Db演示"));
        listButton.add(addButton("权限处理和回传数据演示"));
        listButton.add(addButton("拍照和裁剪演示"));
        listButton.add(addButton("图片选取和裁剪演示"));

        for (Button btn : listButton) {
            btn.setOnClickListener(this);
        }
        dianji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setRemoteDescription(sdp);
            }
        });
    }

    private Button addButton(String text) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                                         ViewGroup.LayoutParams.WRAP_CONTENT);
        Button button = new Button(mActivity);
        button.setText(text);
        button.setGravity(Gravity.CENTER);
        button.setAllCaps(false);
        llContent.addView(button, params);
        return button;
    }

    @Override
    public void onClick(View v) {
        if (v == listButton.get(0)) {
            ActivityUtil.startActivity(this, HttpDemoActivity.class);
        } else if (v == listButton.get(1)) {
//            ActivityUtil.startActivity(this, DbDemoActivity.class);
        } else if (v == listButton.get(2)) {
            PermissionHelper.requestPermission(mActivity,
                                               new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.CAMERA},
                                               new PermissionsResultAction() {
                                                   @Override
                                                   public void onGranted() {
                                                       Intent intent = new Intent(mActivity,
                                                                                  PermissionAndActivityResultActivity.class);
                                                       intent.putExtra("data", "传入数据-xxx");
                                                       startActivityWithCallback(intent, (resultCode, data) -> {
                                                           if (resultCode == RESULT_OK) {
                                                               if (data != null) {
                                                                   Toast.makeText(MainActivity.this,
                                                                                  data.getStringExtra("data"),
                                                                                  Toast.LENGTH_SHORT).show();
                                                               }
                                                           }
                                                       });
                                                   }

                                                   @Override
                                                   public void onDenied(String permission) {
                                                       Toast.makeText(MainActivity.this,
                                                                      "请赋予本程序拨打电话和摄像头权限!",
                                                                      Toast.LENGTH_SHORT).show();
                                                   }
                                               });
        } else if (v == listButton.get(3)) {
            final String savePath = FramePathConst.getInstance().getTempFilePath("jpg");
            SystemIntentUtil.takePhotoWithCrop(mActivity,
                                               savePath,
                                               600,
                                               600,
                                               new SystemIntentUtil.OnCompleteLisenter() {
                                                   @Override
                                                   public void onSelected(Uri fileProviderUri) {
                                                       ImageLoaderUtils.displayImage(mActivity, savePath, imageView);
                                                       System.out.println(fileProviderUri.getPath());
                                                   }

                                                   @Override
                                                   public void onCancel() {

                                                   }
                                               });
        } else if (v == listButton.get(4)) {
            final String savePath = FramePathConst.getInstance().getTempFilePath("jpg");
            SystemIntentUtil.selectPhotoWithCrop(mActivity,
                                                 savePath,
                                                 600,
                                                 600,
                                                 new SystemIntentUtil.OnCompleteLisenter() {
                                                     @Override
                                                     public void onSelected(Uri fileProviderUri) {
                                                         ImageLoaderUtils.displayImage(mActivity,
                                                                                       fileProviderUri,
                                                                                       imageView);
                                                         System.out.println(fileProviderUri.getPath());
                                                     }

                                                     @Override
                                                     public void onCancel() {

                                                     }
                                                 });
        }
    }
    public void inintdate(){

        //初始化EglBase macaruina
        EglBase.Context eglBaseContext = EglBase.create().getEglBaseContext();
        PeerConnectionFactory.initialize(PeerConnectionFactory.InitializationOptions
                .builder(MainActivity.this)
                .createInitializationOptions());
        //初始化PeerConnectionFactory macaruina
        PeerConnectionFactory.Options options = new PeerConnectionFactory.Options();
        DefaultVideoEncoderFactory encoderFactory =
                new DefaultVideoEncoderFactory(eglBaseContext, true, true);
        DefaultVideoDecoderFactory decoderFactory =
                new DefaultVideoDecoderFactory(eglBaseContext);
        PeerConnectionFactory peerConnectionFactory = PeerConnectionFactory.builder()
                .setOptions(options)
                .setVideoEncoderFactory(encoderFactory)
                .setVideoDecoderFactory(decoderFactory)
                .createPeerConnectionFactory();
        //初始化SurfaceViewRenderer
        surfaceViewRenderer.init(eglBaseContext, null);
        //初始化peerConnectionFactory监听 macaruina
        PeerConnection.RTCConfiguration rtcConfig = new PeerConnection.RTCConfiguration(new ArrayList<>());
        //修改模式 PlanB无法使用仅接收音视频的配置
        rtcConfig.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN;
        peerConnection = peerConnectionFactory.createPeerConnection(rtcConfig,
                new PeerConnection.Observer() {


                    @Override
                    public void onSignalingChange(PeerConnection.SignalingState signalingState) {
                        Log.e("mian","onSignalingChange");
                    }

                    @Override
                    public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
                        Log.e("mian","onIceConnectionChange");
                    }

                    @Override
                    public void onIceConnectionReceivingChange(boolean b) {
                        Log.e("mian","onIceConnectionReceivingChange");
                    }

                    @Override
                    public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) {
                        Log.e("mian","onIceGatheringChange");
                    }

                    @Override
                    public void onIceCandidate(IceCandidate iceCandidate) {
                        Log.e("mian","onIceCandidate");
                    }

                    @Override
                    public void onIceCandidatesRemoved(IceCandidate[] iceCandidates) {
                        Log.e("mian","onIceCandidatesRemoved");
                    }

                    @Override
                    public void onAddStream(MediaStream mediaStream) {
                        Log.e("mian","onAddStream");
                        //在这里将流放进surfaceViewRenderer中 macaruina
                        mediaStream.videoTracks.get(0).addSink(surfaceViewRenderer);
                    }

                    @Override
                    public void onRemoveStream(MediaStream mediaStream) {
                        Log.e("mian","onRemoveStream");
                    }

                    @Override
                    public void onDataChannel(DataChannel dataChannel) {
                        Log.e("mian","onDataChannel");
                    }

                    @Override
                    public void onRenegotiationNeeded() {
                        Log.e("mian","onRenegotiationNeeded");
                    }

                    @Override
                    public void onAddTrack(RtpReceiver rtpReceiver, MediaStream[] mediaStreams) {
                        Log.e("mian","onAddTrack");
                    }

                });
        //设置仅接收音视频
        peerConnection.addTransceiver(MediaStreamTrack.MediaType.MEDIA_TYPE_VIDEO, new RtpTransceiver.RtpTransceiverInit(RtpTransceiver.RtpTransceiverDirection.RECV_ONLY));
        peerConnection.addTransceiver(MediaStreamTrack.MediaType.MEDIA_TYPE_AUDIO, new RtpTransceiver.RtpTransceiverInit(RtpTransceiver.RtpTransceiverDirection.RECV_ONLY));

         sdpObserver = new SdpObserver() {
            @Override
            public void onCreateSuccess(SessionDescription sessionDescription) {
                if (sessionDescription.type == SessionDescription.Type.OFFER) {
                    //设置setLocalDescription offer返回sdp macaroni
                    peerConnection.setLocalDescription(sdpObserver, sessionDescription);
                    setRemoteDescription(sdp);
                    //请求SRS服务器接口 macaruina
                    //HttpPost.....网络请求 得到结果后调用setRemoteDescription 传入返回的sdp
                }
            }

            @Override
            public void onSetSuccess() {
                Log.e("mian","onSetSuccess");
            }

            @Override
            public void onCreateFailure(String s) {
                Log.e("mian","onCreateFailure");
            }

            @Override
            public void onSetFailure(String s) {
                Log.e("mian","onSetFailure");
            }
        };
        peerConnection.createOffer(sdpObserver, new MediaConstraints());
    }
    void setRemoteDescription(String sdp) {
        SessionDescription remoteSpd = new SessionDescription(SessionDescription.Type.ANSWER, sdp);
        peerConnection.setRemoteDescription(sdpObserver, remoteSpd);
    }
}
