<!DOCTYPE HTML>
<html>
<head>
  <script type="application/javascript" src="pc.js"></script>
</head>
<body>
<pre id="test">
<script type="application/javascript">
"use strict";

createHTML({
  title: "MediaStream's 'addtrack' and 'removetrack' events with gUM",
  bug: "1208328"
});

runNetworkTest(function (options) {
  let test = new PeerConnectionTest(options);
  let eventsPromise;
  addRenegotiation(test.chain,
    [
      function PC_LOCAL_SWAP_VIDEO_TRACKS(test) {
        return getUserMedia({video: true}).then(stream => {
          var videoTransceiver = test.pcLocal._pc.getTransceivers()[1];
          is(videoTransceiver.currentDirection, "sendonly",
             "Video transceiver's current direction is sendonly");
          is(videoTransceiver.direction, "sendrecv",
             "Video transceiver's desired direction is sendrecv");

          const localStream = test.pcLocal._pc.getLocalStreams()[0];
          ok(localStream, "Should have local stream");

          const remoteStream = test.pcRemote._pc.getRemoteStreams()[0];
          ok(remoteStream, "Should have remote stream");

          const newTrack = stream.getTracks()[0];

          const videoSenderIndex =
            test.pcLocal._pc.getSenders().findIndex(s => s.track.kind == "video");
          isnot(videoSenderIndex, -1, "Should have video sender");

          test.pcLocal.removeSender(videoSenderIndex);
          is(videoTransceiver.direction, "recvonly",
             "Video transceiver should be recvonly after removeTrack");
          test.pcLocal.attachLocalTrack(stream.getTracks()[0], localStream);
          is(videoTransceiver.direction, "recvonly",
             "Video transceiver should be recvonly after addTrack");

          eventsPromise = haveEvent(remoteStream, "addtrack",
              wait(50000, new Error("No addtrack event for " + newTrack.id)))
            .then(trackEvent => {
              ok(trackEvent instanceof MediaStreamTrackEvent,
                 "Expected event to be instance of MediaStreamTrackEvent");
              is(trackEvent.type, "addtrack",
                 "Expected addtrack event type");
              is(trackEvent.track.readyState, "live",
                 "added track should be live");
            })
            .then(() => haveNoEvent(remoteStream, "addtrack"));
        });
      },
    ],
    [
      function PC_REMOTE_CHECK_EVENTS(test) {
        return eventsPromise;
      },
    ]
  );

  test.setMediaConstraints([{audio: true, video: true}], []);
  return test.run();
});
</script>
</pre>
</body>
</html>
