'use strict';

define(function() {
  /*
   * noCfgCtrl
   */
  var noCfgCtrl = function(
    $scope,
    ngDialog,
    DataStoreFactory,
    gaDomUtils,
    AncAppFactory,
    $location,
    ConfigFactory,
    $filter,
    $timeout,
    FeatureTypeFactory,
    $rootScope
  ) {
    $scope.isAdmin = $rootScope.xgos.isadmin;

    $scope.dataStores = false;
    DataStoreFactory.get().then(function() {
      $scope.dataStores = DataStoreFactory.resources.datastores;
    });

    $scope.create_tables = {
      value: true,
    };

    // check if there's really no cfg
    var noCfgDialog;

    if (
      FeatureTypeFactory.getFeatureByNameAndDatastore(
        AncAppFactory.appCfg.main.datastore,
        'kis_anc_dossier'
      ) ||
      AncAppFactory.appCfg.main != ''
    ) {
      $location.path('/anc/');
    } else {
      noCfgDialog = ngDialog.open({
        template: 'js/XG/widgets/ancapp/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 };

    /**
     * init anc application
     */
    $scope.initApp = function() {
      var ans = 1;
      if ($scope.create_tables.value) {
        var ans = confirm(
          $filter('translate')('ancapp.init.confirm_create_tables')
        );
      }

      if (ans) {
        gaDomUtils.showGlobalLoader();

        var appname = $location.search().app;
        var data = {
          datastore: $scope.initDatastore.value,
          properties: {
            filieresVectorielles: {
              active: true,
            },
          },
        };

        var initSuccess = function() {
          $location.path('/anc/');
          $location.search('initdb', 1);

          noCfgDialog.close();
          gaDomUtils.hideGlobalLoader();
        };

        // add cfg
        ConfigFactory.add(data, 'main', 'mainConfig', appname).then(function() {
          // create tables
          if ($scope.create_tables.value) {
            AncAppFactory.initdatabase(appname).then(
              function() {
                require('toastr').success(
                  $filter('translate')('ancapp.init.init_ok')
                );
                $timeout(function() {
                  initSuccess();
                }, 1000);
              },
              function() {
                require('toastr').error(
                  $filter('translate')('ancapp.init.init_nok')
                );
              }
            );
          } else {
            initSuccess();
          }
        });
      }
    };
  };

  noCfgCtrl.$inject = [
    '$scope',
    'ngDialog',
    'DataStoreFactory',
    'gaDomUtils',
    'AncAppFactory',
    '$location',
    'ConfigFactory',
    '$filter',
    '$timeout',
    'FeatureTypeFactory',
    '$rootScope',
  ];
  return noCfgCtrl;
});
