<!DOCTYPE html>
<html lang="en">

<head>
  <base href="/">
  <meta charset="UTF-8">
  <title>Analytics Loader</title>
  <link rel="stylesheet" href="stylesheets/kaltura-theme.css">
  <link rel="stylesheet" href="stylesheets/style.css">
</head>

<body>
  <h1>This is an external app loading Analytics in an iframe</h1>
  <div class="selectDiv">
    <h2 style="display: inline;">Select Analytics Report: </h2>
    <select id="listOfViews" disabled="1" style="font-size: 1.3em;">
      <option value="loading">Loading Analytics Views...</option>
    </select>
  </div>

  <div class="selectDiv">

    <h2 style="display: inline;">Object ID (entry/entryLive/playlist/user): </h2>
    <input title="ID or user email of the object in details report" type="text" id="detailObjId"
      style="font-size: 1.3em;">
    <br /><br />

    <h2 style="display: inline;">Select Analytics Report: </h2>
    <select id="detailViews" disabled="1" style="font-size: 1.3em;">
      <option value="loading">Loading Analytics Views...</option>
    </select>
    <button id="btnDetail">Go</button>
  </div>

  <iframe id="analytics" src="https://kmc.kaltura.com/apps/kmc-analytics/v1.12.0/index.html"></iframe>
  <script>
    var config = {
      kalturaServer: {
        uri: 'www.kaltura.com',
        previewUIConf: <%=process.env.KALTURA_UICONF_ID %>
      },
      cdnServers: {
        serverUri: 'http://cdnapi.kaltura.com',
        securedServerUri: 'https://cdnapisec.kaltura.com'
      },
      ks: "<%=ks%>",
      pid: <%=process.env.KALTURA_PARTNER_ID %>,
      locale: 'en',
      menuConfig: {
        showMenu: false
      },
    };

    document.addEventListener('DOMContentLoaded', () => {
      var analyticsApp = document.getElementById('analytics');

      var sendMessage = message => {
        if (analyticsApp && analyticsApp.contentWindow && analyticsApp.contentWindow.postMessage) {
          analyticsApp.contentWindow.postMessage(message, '*'); // use window.location.origin in your app instead
        }
      };

      //listen for events from analytics API
      window.addEventListener('message', e => {
        if (!e.data) {
          return;
        }

        var postMessageData = e.data;
        switch (postMessageData.messageType) {
          case 'analyticsInit':
            var menusConfig = postMessageData.payload.menuConfig;
            var viewsConfig = postMessageData.payload.viewsConfig;

            //To remove items from the views, simply set them to null
            //for example, to remove the page title and back button from the top of playlist details report, use -
            //viewsConfig.playlist.title = null;
            //example 2, to remove the Last Viewed Entries from the  user details report, use - 
            //viewsConfig.user.lastViewedEntries = null;

            //initialize the analytics app iframe content
            sendMessage({ messageType: 'init', payload: { ...config, viewsConfig } })

            var selectPaths = {};
            //Parse through the API's list of report types to build the selectPaths objects
            //which is used to build an html select form so the user can choose different types of analytics views.
            Object.keys(menusConfig).forEach(function (key) {
              if (menusConfig[key].hasOwnProperty('items')) {
                Object.keys(menusConfig[key].items).forEach(function (key2) {
                  if (menusConfig[key].id == 'bandwidth')
                    selectPaths[menusConfig[key].items[key2].link] = 'infra usage: ' + menusConfig[key].items[key2].id;
                  else
                    selectPaths[menusConfig[key].items[key2].link] = menusConfig[key].items[key2].id;
                });
              } else
                selectPaths[menusConfig[key].link] = menusConfig[key].id;
            });

            var detailPaths = {};
            //these are the paths from selectPaths that pertain to screens
            //that require specific id's aka the detail views
            var detailKeys = ['entry', 'entryLive', 'playlist', 'user'];
            Object.keys(viewsConfig).forEach(function (key) {
              //Skip general views (already included above in menus) - audience, bandwidth, contributors
              //We parse views to get the list of object-detail-level analytics, such as end-user or entry specific
              if (detailKeys.includes(key)) {
                detailPaths[key] = 'details report: ' + key;
              }
            });

            //viewSelect is a dropDown for general screens pertaining to the whole account
            //versus detailSelect which is analytics for specific objects
            var viewsSelect = document.getElementById("listOfViews");
            viewsSelect.options.length = 0;
            for (index in selectPaths) {
                viewsSelect.options[viewsSelect.options.length] = new Option(selectPaths[index], index);
            }
            viewsSelect.disabled = false;
            viewsSelect.onchange = function (e) {
              var path = e.target.value;
              sendMessage({ messageType: 'navigate', payload: { url: path } });
              sendMessage({ messageType: 'updateFilters', payload: { queryParams: { dateBy: 'last30days' } } });
            }

            //detailSelect is a dropDown for analytics for specific object id's
            var detailSelect = document.getElementById("detailViews");
            detailSelect.options.length = 0;
            for (index in detailPaths) {
                detailSelect.options[detailSelect.options.length] = new Option(detailPaths[index], index);
            }

            detailSelect.disabled = false;
            var btnDetail = document.getElementById("btnDetail");
            btnDetail.onclick = function (e) {
              //code for specific text input
              var detailObjId = document.getElementById("detailObjId");
              var path = detailSelect.value + '/' + detailObjId.value;
              sendMessage({ messageType: 'navigate', payload: { url: path } });
              sendMessage({ messageType: 'updateFilters', payload: { queryParams: { dateBy: 'last30days' } } });
            }
            break;

          case 'navigateBack':
          case 'analyticsInitComplete':
            // Example: To get the overall engagement reports across all content, use:
            sendMessage({ messageType: 'navigate', payload: { url: '/audience/engagement' } });
            // Example: To get unique user ID engagement dashboard, use:
            //sendMessage({ messageType: 'navigate', payload: { url: '/user/xyz@kaltura.com' } });
            sendMessage({ messageType: 'updateFilters', payload: { queryParams: { dateBy: 'last30days' } } });
            break;

          case 'updateLayout':
            analyticsApp.style.height = `${postMessageData.payload.height}px`;
            break;

          case 'navigateTo':
            var [url, params] = postMessageData.payload.split('?');
            var queryParams = params.split('&').reduce((acc, val) => {
              var [key, value] = val.split('=');
              acc[key] = value;
              return acc;
            }, {});

            sendMessage({ 'messageType': 'navigate', payload: { url, queryParams } });
            sendMessage({ 'messageType': 'updateFilters', payload: { queryParams } });
            break;

          default:
            console.log(`${postMessageData.messageType} event is not implemented`);
            break;
        }
      })
    });
  </script>
</body>

</html>