(function () {
  'use strict';

  /**
   * Service for taking screenshots.
   */
  function twxPictureService(tml3dRenderer) {
    return {
      restrict: 'E',
      link: function (scope, el) {
        // Add an element for flashing efect used when taking pictures.
        const flashEl = document.createElement('div');
        flashEl.classList.add('take-screenshot-flash', 'take-screenshot-flash-fade');
        document.querySelector('twx-dt-view').appendChild(flashEl);

        scope.$on('serviceInvoke', function (event, data) {
          const name = data.serviceName;
          if (scope.services[name]) {
            scope.services[name](data.params);
          }
        });

        scope.services = {
          /**
           * Takes screenshot of current view.
           */
          takePicture: function () {
            if (!tml3dRenderer.takeScreenshot) {
              console.error('takePicture: tml3dRenderer.takeScreenshot not available');
              return;
            }

            console.log('takePicture: tml3dRenderer.takeScreenshot available, calling...');
            const imgFormat = 'JPEG';
            const config = {
              withAugmentation: !scope.me.isAugmentationsHidden,
              imgFormat: imgFormat,
            };

            tml3dRenderer.takeScreenshot(config, function success(data, params) {
              console.log('takePicture: tml3dRenderer.takeScreenshot succeeded');
              flash();
              scope.me.image = data;

              const dataUrlPrefix = 'data:image/' + imgFormat.toLowerCase() + ';base64,';
              scope.me.imageUrl = dataUrlPrefix + data;

              scope.$emit('pictureTaken', { data: data, params: params });
              scope.$apply();
            }, function failure() {
              // User clicked the cancel/close icon, do not take the picture.
              scope.$emit('userCanceled');
              scope.$apply();
              console.log('takePicture: tml3dRenderer.takeScreenshot cancelled');
            });
          }
        };

        function flash() {
          // Class change triggers css transition.
          flashEl.classList.remove('take-screenshot-flash-fade');
          setTimeout(() => {
            flashEl.classList.add('take-screenshot-flash-fade');
          });
        }
      }
    };
  }

  angular.module('ngPictureService', ['vuforia-angular'])
    .directive('twxPictureService', [ 'tml3dRenderer', twxPictureService ]);
}());
