'use strict';

define(function() {
  /*
   * noCfgCtrl
   */
  var noCfgCtrl = function(
    $scope,
    ngDialog,
    DataStoreFactory,
    gaDomUtils,
    SirocoFactory,
    $location
  ) {
    $scope.dataStores = false;
    DataStoreFactory.get().then(function() {
      $scope.dataStores = DataStoreFactory.resources.datastores;
    });

    // check if there's really no cfg
    var noCfgDialog;
    if ($location.$$path == '/siroco/nocfg')
      noCfgDialog = ngDialog.open({
        template: 'js/XG/widgets/sirocoapp/main/views/modals/modal.nocfg.html',
        className:
          'ngdialog-theme-plain width800 nopadding miniclose error_dialog',
        closeByDocument: false,
        showClose: false,
        scope: $scope,
      });
    else
      SirocoFactory.getSirocoCfg().then(
        // cfg found, go back home
        function(res) {
          $location.path('/siroco/');
          // ok there's no cfg, launch modal
        },
        function() {
          noCfgDialog = ngDialog.open({
            template:
              'js/XG/widgets/sirocoapp/main/views/modals/modal.nocfg.html',
            className:
              'ngdialog-theme-plain width800 nopadding miniclose error_dialog',
            closeByDocument: false,
            showClose: false,
            scope: $scope,
          });
        }
      );

    $scope.initDatastore = { value: false };
    $scope.initDatabase = function() {
      gaDomUtils.showGlobalLoader();

      SirocoFactory.initializedatabase($scope.initDatastore.value).then(
        function() {
          SirocoFactory.getSirocoCfg().then(function() {
            $location.path('/siroco/');
            noCfgDialog.close();
            gaDomUtils.hideGlobalLoader();
          });
        },
        function(res) {
          require('toastr').error(res.data.errorMessage, 'Erreur', {
            closeButton: true,
            timeOut: '0',
            extendedTimeOut: '0',
            positionClass: 'toast-bottom-full-width',
          });
          gaDomUtils.hideGlobalLoader();
        }
      );
    };
  };

  noCfgCtrl.$inject = [
    '$scope',
    'ngDialog',
    'DataStoreFactory',
    'gaDomUtils',
    'SirocoFactory',
    '$location',
  ];
  return noCfgCtrl;
});
