'use strict';

let modulesPageController = BaseBuildController.extend({
  init: function ($scope, modulesService, projectsService, $routeParams, $modal, masterfilesversionService) {
    this._super($scope, projectsService, $routeParams, $modal);

    $scope.moduleName = $routeParams.name;
    this.$modal = $modal;
    this.projectsService = projectsService;
    this.modulesService = modulesService;
    this.masterfilesVersionService = masterfilesversionService;
  },

  defineListeners: function () {
    this._super();
    let self = this;

    this.$scope.$watch('addedModules', function () {
      if (self.$scope.addedModules == undefined) return;
      self.$scope.addedVersion = null;
      self.$scope.addedModules.forEach(item => {
        if (item.name == self.$scope.moduleName && item.version) {
          self.$scope.addedVersion = item.version;
        }
      });
    });

    this.$scope.$watch('addedVersion', function () {
      if (self.$scope.addedVersion === undefined) return;

      common.globalSpinner.show();
      self.modulesService.get(self.$scope.moduleName, self.$scope.addedVersion).then(
        response => {
          self.$scope.module = response.data;
          self.$scope.module.addedVersion = self.$scope.addedVersion;
          Object.keys(self.$scope.module.versions).forEach(version => {
            if (self.$scope.module.versions[version].latest === true) {
              self.$scope.module.latestVersion = version;
            }
          });

          self.$scope.module.updated = new Date(self.$scope.module.updated).toLocaleString('default', {
            month: 'short',
            day: 'numeric',
            year: 'numeric'
          });
          self.$scope.module.readme = htmlSpecialCharsDecode(self.$scope.module.readme);
          common.globalSpinner.hide();
        },
        error => {
          if (error.status == 404) {
            notify.error('Module not found.');
            common.globalSpinner.hide();
          }
        }
      );
    });

    self.$scope.$on('module_data_saved', function () {
      self.refreshProjectStatus();
      self.loadProjectInfo(self.$scope.projectID);
    });
  },

  defineScope: function () {
    this.$scope.instance = 'modulesPageController';

    this.$scope.openUpdateDialog = this.openUpdateDialog.bind(this);
    this.$scope.addModule = this.addModule.bind(this);
    this.$scope.removeModule = this.removeModule.bind(this);
  },

  openUpdateDialog: function () {
    let self = this;
    this.modalInstance = this.$modal.open({
      templateUrl: 'confirmModuleUpdate.html',
      backdrop: 'static',
      keyboard: true,
      windowClass: 'update-module-dialog',
      controller: function ($scope, $modalInstance, $parent) {
        $scope.module = $parent.$scope.module;
        $scope.commitMessage = `Updated ${$scope.module.name}\ from ${$scope.module.addedVersion}\ to ${$scope.module.latestVersion}`;
        $scope.close = function () {
          $modalInstance.close('cancel');
        };
        $scope.update = function () {
          common.globalSpinner.show();
          self.projectsService.updateModule(self.$scope.projectID, self.$scope.module.name, self.$scope.module.latestVersion).then(
            () => {
              notify.success('Module successfully updated.');
              self.refreshProjectStatus();
              self.loadProjectInfo(self.$scope.projectID);
              self.$scope.addedVersion = self.$scope.module.latestVersion;
              $modalInstance.close('cancel');
              common.globalSpinner.hide();
            },
            error => {
              displayError(error, this.$scope);
              common.globalSpinner.hide();
              $modalInstance.close('cancel');
            }
          );
        };
      },
      resolve: {
        $parent: function () {
          return self;
        }
      }
    });
  },
  addModule: function () {
    if (this.$scope.module.name === MASTERFILES_MODULE) {
      this.masterfilesVersionService.getVersion().then(version => {
        const moduleData = this.prepareModuleData({
          projectID: this.$scope.projectID,
          name: this.$scope.module.name,
          version
        });
        this.addModule(moduleData);
      });
    } else {
      this.addModule({ projectID: this.$scope.projectID, name: this.$scope.module.name, version: this.$scope.module.version });
    }
  }
});

modulesPageController.$inject = ['$scope', 'modulesService', 'projectsService', '$routeParams', '$modal', 'masterfilesversionService'];

let externalModulesPageController = BaseBuildController.extend({
  init: function ($scope, projectsService, $routeParams, $modal) {
    this._super($scope, projectsService, $routeParams, $modal);
    $scope.moduleName = atob($routeParams.name);
    this.$modal = $modal;
  },

  defineListeners: function () {
    this._super();
    let self = this;

    this.$scope.$watch(
      'addedModules',
      function (addedModules) {
        if (addedModules == undefined) {
          return;
        }
        addedModules.forEach(module => {
          if (module.name == self.$scope.moduleName) {
            self.$scope.module = module;
            self.$scope.module.external = true;
            self.$scope.module.addedVersion = self.$scope.module.version;
          }
        });
      },
      true
    );
  },

  defineScope: function () {
    this.$scope.instance = 'externalModulesPageController';

    this.$scope.removeModule = this.removeModule.bind(this);
  }
});

externalModulesPageController.$inject = ['$scope', 'projectsService', '$routeParams', '$modal'];
