'use strict';

define(function() {
  /*
   * documentsCtrl
   */
  var documentsCtrl = function(
    $scope,
    DocumentFactory,
    AncAppFactory,
    gaDomUtils,
    IndicatorParamsFactory,
    PortalsFactory
  ) {
    //GET dashboardCfg
    $scope.dashboardCfg = AncAppFactory.appCfg.main.dashboardCfg;

    if (!$scope.dashboardCfg) {
      $scope.dashboardCfg = [];
    }

    /**
     * getDocx (modele)
     * @param fichier
     */
    $scope.getDocx = function(fichier) {
      gaDomUtils.showGlobalLoader();
      DocumentFactory.generatedocx('{}', fichier).then(function(res) {
        window.open(
          '/services/' +
            res.data.portalid +
            '/documents/downloaddocx?' +
            '&name=' +
            res.data.name +
            '&token=' + encodeURIComponent(localStorage.getItem('auth_token'))
        );
        gaDomUtils.hideGlobalLoader();
      });
    };

    /**
     * getStaticFIle (static)
     * @param fichier
     */
    $scope.getStaticFIle = function(fichier) {
      window.open(
        '/services/' +
          PortalsFactory.getPortalId() +
          '/ancapp/downloaddashboarddoc?type=static' +
          '&name=' +
          fichier +
          '&bacapp=' +
          '&token=' + encodeURIComponent(localStorage.getItem('auth_token'))
      );
    };

    /**
     * getJasperReport (static)
     * @param fichier
     */
    $scope.getJasperReport = function(rapport) {
      var jsonParameters = IndicatorParamsFactory.buildJsonParams(
        rapport.indicateurs
      );
      gaDomUtils.showGlobalLoader();

      var nameWeExt = rapport.fichier.replace('.jasper', '');
      AncAppFactory.generatereport(nameWeExt, jsonParameters).then(
        function(res) {
          window.open(
            '/services/' +
              PortalsFactory.getPortalId() +
              '/ancapp/getreportpdf?filename=' +
              nameWeExt +
              '&bacapp=' +
              '&token=' + encodeURIComponent(localStorage.getItem('auth_token'))
          );
          gaDomUtils.hideGlobalLoader();
        },
        function(reason) {
          gaDomUtils.hideGlobalLoader();
          require('toastr').error('Erreur lors de la génération du rapport.');
        }
      );
    };
  };

  documentsCtrl.$inject = [
    '$scope',
    'DocumentFactory',
    'AncAppFactory',
    'gaDomUtils',
    'IndicatorParamsFactory',
    'PortalsFactory'
  ];
  return documentsCtrl;
});
