'use strict';
define(function () {
  var logoToolbar = function (
    ApplicationFactory,
    gaDomUtils,
    $filter
  ) {
    return {
      templateUrl:
        'js/XG/widgets/mapapp/logo/views/logoToolbar.html',
      restrict: 'A',
      link: function (scope) {
        scope.positionOptions = [{
          title: 'toolbar_logo.position.bottomLeft',
          value: 'bottomLeft'
        }, {
          title: 'toolbar_logo.position.topLeft',
          value: 'topLeft'
        }, {
          title: 'toolbar_logo.position.topRight',
          value: 'topRight'
        }];
        scope.uploadedFile = (file) => {
          if (file && file.xhr) {
            scope.app.logo.path = file.xhr.response;
          }
        }
        scope.saveLogo = () => {
          if (!scope.app.logo.path) {
            require('toastr').error($filter('translate')('toolbar_logo.image_required'));
            return;
          }
          gaDomUtils.showGlobalLoader();
          ApplicationFactory.update(scope.app)
            .then(() => {
              scope.$parent.appData = angular.copy(scope.app);
              require('toastr').success($filter('translate')('toolbar_logo.saved'));
              closeToolbar();
            })
            .catch(() => {
              require('toastr').error($filter('translate')('toolbar_logo.save_failed'));
            })
            .finally(() => {
              gaDomUtils.hideGlobalLoader();
            });
        }

        scope.getFileName = (path) => {
          return ((path.split('?')[1] || '').split('&').find(queryParam => queryParam.indexOf('fileName=') !== -1) || '').replace('fileName=', '');
        }

        if (ApplicationFactory.resources.applications && ApplicationFactory.resources.applications.length) {
          initApp();
        } else {
          ApplicationFactory.get().then(() => initApp());
        }
        function initApp() {
          scope.app = angular.copy(
            ApplicationFactory.resources.applications.find(application => application.name === scope.$parent.app)
          );
          scope.app.logo = Object.assign({
            position: 'bottomLeft'
          }, scope.app.logo || {});
        }
        function closeToolbar() {
          if (!scope.isActive) { $('#toolbar_map_logo_popover').click(); }
          scope.isActive = !scope.isActive;
        }
      },
    };
  };

  logoToolbar.$inject = [
    'ApplicationFactory',
    'gaDomUtils',
    '$filter'
  ];
  return logoToolbar;
});
