<!DOCTYPE html>

<meta charset="utf-8">
<title>Establishing a presentation connection</title>
<link rel="author" title="Intel" href="http://www.intel.com">
<link rel="author" title="He Yue" href="mailto:yue.he@intel.com">
<link rel="author" title="Tomoyuki Shimizu" href="https://github.com/tomoyukilabs/">
<link rel="help" href="https://w3c.github.io/presentation-api/#establishing-a-presentation-connection">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="common.js"></script>
<h2>Description</h2>
<p>
  This test validates that after connection starts,<br/>
  the onconnect EventHandler is triggered and connection state is connected.
</p>
<br/>
<p>Click the button below to start the test.</p>
<button id="presentBtn">Start Presentation Test</button>

<script>
  setup({explicit_timeout: true});

  const presentBtn = document.getElementById('presentBtn');

  promise_test(t => {
    const clickWatcher = new EventWatcher(t, presentBtn, 'click');
    const request = new PresentationRequest(presentationUrls);
    let connection;

    t.add_cleanup(() => {
      if (connection) {
        connection.onconnect = () => { connection.terminate(); };
        if (connection.state === 'closed')
          request.reconnect(connection.id);
        else
          connection.terminate();
      }
    });

    const watchEvent = (obj, watcher, type) => {
      const watchHandler = new Promise(resolve => {
        obj['on' + type] = evt => { resolve(evt); };
      });
      return Promise.all([ watchHandler, watcher.wait_for(type) ]).then(results => {
        assert_equals(results[0], results[1], 'Both on' + type + ' and addEventListener pass the same event object.');
        return results[0];
      });
    };

    return clickWatcher.wait_for('click').then(() => {
      presentBtn.disabled = true;

      return request.start();
    }).then(c => {
      // Enable timeout again, cause no user action is needed from here.
      t.step_timeout(() => {
          t.force_timeout();
          t.done();
      }, 5000);

      connection = c;
      const eventWatcher = new EventWatcher(t, connection, 'connect');
      return watchEvent(connection, eventWatcher, 'connect');
    }).then(evt => {
      assert_true(evt.isTrusted && !evt.bubbles && !evt.cancelable && evt instanceof Event, 'A simple event is fired.');
      assert_equals(evt.type, 'connect', 'The event name is "connect".');
      assert_equals(evt.target, connection, 'event.target is the presentation connection.');
      assert_equals(connection.state, 'connected', 'The presentation connection state is set to "connected".');
    });
  });
</script>
