<!DOCTYPE html>
<html>
<head>
    <title>clearkey</title>
    <script src=../../media-resources/video-test.js></script>
    <script src="support.js"></script>
    <script>
        var keyId;
        var session;

        function go()
        {
            findMediaElement();
            waitForEvent('webkitneedkey', needkey);
            video.src = '../resources/hls/clearkey/prog_index.m3u8';
        }

        function needkey(event)
        {
            if (!video.webkitKeys)
                video.webkitSetMediaKeys(new WebKitMediaKeys('org.w3c.clearkey'));

            if (!video.webkitKeys) {
                log('Error: org.w3c.clearkey not supported.');
                return;
            }

            session = video.webkitKeys.createSession('application/x-mpegurl', event.initData);
            waitForEventOnceOn(session, 'webkitkeymessage', onkeymessage);
            waitForEventOnceOn(session, 'webkitkeyerror', onkeyerror);
            waitForEventOnceOn(session, 'webkitkeyadded');
        }

        function onkeymessage(e)
        {
            var request = new XMLHttpRequest();
            request.responseType = 'arraybuffer';
            waitForEventOnceOn(request, 'load', keyDataLoaded);
            waitForEventOnceOn(request, 'error', keyDataLoadingFailed);

            keyId = uInt8ArrayToString(event.message);
            request.open('GET', '../resources/hls/clearkey/' + keyId, true);
            request.send();
        }

        function onkeyerror(e) { failTest('Received keyerror'); }

        function keyDataLoadingFailed(e)
        {
            failTest('Received an error loading key file');
        }

        function keyDataLoaded(e)
        {
            var request = e.target;
            var keyData = new Uint8Array(request.response);

            var responseObject = {
                keys: [{
                    'kty': 'oct',
                    'alg': 'A128KW',
                    'kid': keyId,
                    'k': base64EncodeUint8Array(keyData)
                }]
            };
            var responseString = JSON.stringify(responseObject);
            var responseData = stringToUInt8Array(responseString);

            waitForEvent('canplay', oncanplay);
            session.update(responseData);
        }

        function oncanplay(e) { endTest(); }
    </script>
</head>
<body onload="go()">
    <video controls></video>
</body>
</html>