/**
 * @file
 * Visitors behaviors.
 */

(function visitorsTrack(Drupal, drupalSettings, once) {
  /**
   * Attach visitors tracking behaviors.
   */
  Drupal.behaviors.visitorsTracker = {
    attach() {
      once('visitorsTracker', 'html').forEach(function visitors() {
        window._paq = window._paq || [];

        const { _paq } = window;
        const u = drupalSettings.path.baseUrl;
        const path = `/${drupalSettings.path.currentPath}`;
        const { uid } = drupalSettings.user;
        const { route, server, module, counter, title, event } =
          drupalSettings.visitors;

        function visitorsTracker() {
          _paq.push(['setSiteId', 1]);
          _paq.push(['setTrackerUrl', `${u}_visitors`]);
          _paq.push(['setUserId', uid]);
          if (title) {
            _paq.push(['setDocumentTitle', title]);
          }

          _paq.push(['setCustomVariable', 1, 'route', route, 'page']);
          _paq.push(['setCustomVariable', 2, 'path', path, 'page']);
          _paq.push(['setCustomVariable', 3, 'server', server, 'page']);
          if (counter) {
            _paq.push(['setCustomVariable', 4, 'viewed', counter, 'page']);
          }

          if (event) {
            if (event.plugin) {
              _paq.push([
                'setCustomVariable',
                5,
                'plugin',
                event.plugin,
                'event',
              ]);
            }
            if (event.event) {
              _paq.push([
                'setCustomVariable',
                6,
                'event',
                event.event,
                'event',
              ]);
            }
            if (event.variables) {
              Object.keys(event.variables).forEach((key, index) => {
                _paq.push([
                  'setCustomVariable',
                  index + 7,
                  key,
                  event.variables[key],
                  'event',
                ]);
              });
            }
          }

          _paq.push(['trackPageView']);

          const d = document;
          const g = d.createElement('script');
          const s = d.getElementsByTagName('script')[0];

          g.type = 'text/javascript';
          g.defer = true;
          g.async = true;
          g.src = `${module}/js/tracker.min.js`;

          s.parentNode.insertBefore(g, s);
        }

        window.addEventListener('load', function tracker() {
          visitorsTracker();
        });
      });
    },
  };
})(Drupal, drupalSettings, once);
