'use strict';

const masterfilesVersionServiceClass = Class.extend({
  getVersion: function () {
    let deferred = this.$q.defer();

    this.modalInstance = this.$modal.open({
      templateUrl: 'masterfilesVesions.html',
      backdrop: 'static',
      keyboard: true,
      controller: function ($scope, $modalInstance, $parent, deferred, modulesService, hubManagementService) {
        $scope.data = {};
        $scope.versions = [];

        hubManagementService.getHubInfo().then(({ data: { release } }) => ($scope.release = release));

        common.globalSpinner.show();
        modulesService.refreshList().then(() => {
          modulesService.get('masterfiles').then(({ data: { versions } }) => {
            $scope.masterfilesVersions = versions;
            common.globalSpinner.hide();
          });
        });

        const deriveMasterfilesVersionOptions = () => {
          const { version: releaseVersion, isAlpha } = $scope.release;
          const [latestVersion] = Object.keys($scope.masterfilesVersions).filter(version => $scope.masterfilesVersions[version].latest);

          const masterOption = { 'label': 'Master branch', version: 'master' };
          const latestOption = { 'label': 'Latest (' + latestVersion + ')', version: latestVersion };

          const setSelectedAndPushVersions = (selected, fallbackVersion) => {
            $scope.data.selected = selected;
            $scope.versions.push(selected);
            fallbackVersion.forEach(version => $scope.versions.push(version));
          };

          // if CFEngine release version matches master files, then make this version as default
          if ($scope.masterfilesVersions.hasOwnProperty(releaseVersion)) {
            const matchedVersion = { 'label': releaseVersion, version: releaseVersion };
            const { latest } = $scope.masterfilesVersions[releaseVersion];
            // if the matched version is the latest then fallback is only master
            setSelectedAndPushVersions(matchedVersion, latest ? [masterOption] : [latestOption, masterOption]);
          } else if (isAlpha) {
            // if CFEngine is alpha version then default option is master masterfiles
            setSelectedAndPushVersions(masterOption, [latestOption]);
          } else {
            // if there no matched version and no alpha then make latest version as default chose
            setSelectedAndPushVersions(latestOption, [masterOption]);
          }
        };

        $scope.$watchCollection('[release, masterfilesVersions]', () => {
          if ($scope.release && $scope.masterfilesVersions) {
            deriveMasterfilesVersionOptions();
          }
        });

        $scope.close = function () {
          $modalInstance.close();
          deferred.reject();
        };

        $scope.confirm = () => {
          deferred.resolve($scope.data.selected.version);
          $modalInstance.close();
        };
      },
      resolve: {
        $parent: function () {
          return this;
        },
        deferred: function () {
          return deferred;
        },
        modulesService: () => this.modulesService,
        hubManagementService: () => this.hubManagementService
      }
    });

    return deferred.promise;
  }
});

(function () {
  const masterfilesVersionServiceClassProvider = Class.extend({
    instance: new masterfilesVersionServiceClass(),
    $get: [
      '$http',
      '$q',
      '$modal',
      'modulesService',
      'hubManagementService',
      function ($http, $q, $modal, modulesService, hubManagementService) {
        this.instance.$http = $http;
        this.instance.$q = $q;
        this.instance.$modal = $modal;
        this.instance.modulesService = modulesService;
        this.instance.hubManagementService = hubManagementService;
        return this.instance;
      }
    ]
  });

  angular.module('masterfilesVersionServiceModule', []).provider('masterfilesversionService', masterfilesVersionServiceClassProvider);
})();
