'use strict';

let angular = require('angular');

import {V2_MODAL_WIZARD_SERVICE} from 'core/modal/wizard/v2modalWizard.service';
import {ACCOUNT_SERVICE} from 'core/account/account.service';
import {LOAD_BALANCER_READ_SERVICE} from 'core/loadBalancer/loadBalancer.read.service';
import {SECURITY_GROUP_READER} from 'core/securityGroup/securityGroupReader.service';
import {SECURITY_GROUP_WRITER} from 'core/securityGroup/securityGroupWriter.service';
import {TASK_MONITOR_BUILDER} from 'core/task/monitor/taskMonitor.builder';

module.exports = angular.module('spinnaker.securityGroup.kubernetes.create.controller', [
  require('angular-ui-router'),
  LOAD_BALANCER_READ_SERVICE,
  SECURITY_GROUP_READER,
  SECURITY_GROUP_WRITER,
  ACCOUNT_SERVICE,
  V2_MODAL_WIZARD_SERVICE,
  TASK_MONITOR_BUILDER,
  require('../../../namespace/selectField.directive.js'),
  require('../../transformer.js'),
])
  .controller('kubernetesUpsertSecurityGroupController', function($q, $scope, $uibModalInstance, $state,
                                                                  application, securityGroup,
                                                                  accountService, kubernetesSecurityGroupTransformer, securityGroupReader, loadBalancerReader,
                                                                  v2modalWizardService, securityGroupWriter, taskMonitorBuilder) {
    var ctrl = this;
    $scope.isNew = !securityGroup.edit;
    $scope.securityGroup = securityGroup;

    $scope.pages = {
      basicSettings: require('./basicSettings.html'),
      backend: require('./backend.html'),
      rules: require('./rules.html'),
    };

    $scope.state = {
      accountsLoaded: false,
      securityGroupNamesLoaded: false,
      submitting: false
    };

    function onApplicationRefresh() {
      // If the user has already closed the modal, do not navigate to the new details view
      if ($scope.$$destroyed) {
        return;
      }
      $uibModalInstance.close();
      var newStateParams = {
        name: $scope.securityGroup.name,
        accountId: $scope.securityGroup.account,
        namespace: $scope.securityGroup.namespace,
        provider: 'kubernetes',
      };
      if (!$state.includes('**.securityGroupDetails')) {
        $state.go('.securityGroupDetails', newStateParams);
      } else {
        $state.go('^.securityGroupDetails', newStateParams);
      }
    }

    function onTaskComplete() {
      application.securityGroups.refresh();
      application.securityGroups.onNextRefresh($scope, onApplicationRefresh);
    }

    $scope.taskMonitor = taskMonitorBuilder.buildTaskMonitor({
      application: application,
      title: ($scope.isNew ? 'Creating ' : 'Updating ') + 'your security group',
      modalInstance: $uibModalInstance,
      onTaskComplete: onTaskComplete,
    });

    var allSecurityGroupNames = {};

    function getLoadBalancerNames(loadBalancers) {
      return _.chain(loadBalancers)
        .filter({ account: $scope.securityGroup.account })
        .filter({ namespace: $scope.securityGroup.namespace })
        .map('name')
        .flattenDeep()
        .uniq()
        .value();
    }

    function initializeCreateMode() {
      return $q.all({
        accounts: accountService.listAccounts('kubernetes'),
        loadBalancers: loadBalancerReader.listLoadBalancers('kubernetes'),
      }).then(function(backingData) {
        $scope.accounts = backingData.accounts;
        $scope.state.accountsLoaded = true;

        var accountNames = _.map($scope.accounts, 'name');
        if (accountNames.length && !accountNames.includes($scope.securityGroup.account)) {
          $scope.securityGroup.account = accountNames[0];
        }

        ctrl.accountUpdated();
      });
    }

    function initializeSecurityGroupNames() {
      securityGroupReader.loadSecurityGroups('kubernetes').then(function (securityGroups) {
        for (var account in securityGroups) {
          if (!allSecurityGroupNames[account]) {
            allSecurityGroupNames[account] = {};
          }

          let securityGroupsByAccount = securityGroups[account];
          for (var namespace in securityGroupsByAccount) {
            if (!allSecurityGroupNames[account][namespace]) {
              allSecurityGroupNames[account][namespace] = [];
            }

            let securityGroupsByNamespace = securityGroupsByAccount[namespace];
            for (var found in securityGroupsByNamespace) {
              allSecurityGroupNames[account][namespace].push(found);
            }
          }
        }

        updateSecurityGroupNames();
        $scope.state.securityGroupNamesLoaded = true;
      });
    }

    function updateSecurityGroupNames() {
      var account = $scope.securityGroup.account;

      if (allSecurityGroupNames[account]) {
        $scope.existingSecurityGroupNames = _.flatten(_.map(allSecurityGroupNames[account]));
      } else {
        $scope.existingSecurityGroupNames = [];
      }
    }

    if ($scope.isNew) {
      $scope.securityGroup = kubernetesSecurityGroupTransformer.constructNewSecurityGroupTemplate();
    }

    initializeSecurityGroupNames();
    initializeCreateMode();

    // Controller API
    this.updateName = function() {
      $scope.securityGroup.name = this.getName();
      $scope.securityGroup.securityGroupName = this.getName();
    };

    this.getName = function() {
      var securityGroup = $scope.securityGroup;
      var securityGroupName = [application.name, (securityGroup.stack || ''), (securityGroup.detail || '')].join('-');
      return _.trimEnd(securityGroupName, '-');
    };

    this.accountUpdated = function() {
      $q.all({
        accountDetails: accountService.getAccountDetails($scope.securityGroup.account),
        loadBalancers: loadBalancerReader.listLoadBalancers('kubernetes'),
      }).then(function(backingData) {
        $scope.namespaces = backingData.accountDetails.namespaces;
        $scope.loadBalancers = getLoadBalancerNames(backingData.loadBalancers);
        ctrl.namespaceUpdated();
      });
    };

    this.namespaceUpdated = function() {
      updateSecurityGroupNames();
      ctrl.updateName();
    };

    this.submit = function () {
      var descriptor = $scope.isNew ? 'Create' : 'Update';

      this.updateName();
      $scope.taskMonitor.submit(
        function() {
          let params = {
            cloudProvider: 'kubernetes',
            region: $scope.securityGroup.namespace,
          };
          return securityGroupWriter.upsertSecurityGroup($scope.securityGroup, application, descriptor, params);
        }
      );
    };

    this.cancel = function () {
      $uibModalInstance.dismiss();
    };
  });

@@ -5651,41 +5651,8 @@
     
- $q.all(%7B%0A        accountDetails:
  acc
@@ -5710,17 +5710,16 @@
 account)
-,
 %0A       
@@ -5723,83 +5723,8 @@
     
-loadBalancers: loadBalancerReader.listLoadBalancers('kubernetes'),%0A      %7D)
 .the
@@ -5730,39 +5730,44 @@
 en(function(
-b
 ac
-kingData
+countDetails
 ) %7B%0A
+  
         $sco
@@ -5778,36 +5778,24 @@
 amespaces = 
-backingData.
 accountDetai
@@ -5815,86 +5815,8 @@
 ;%0A  
-      $scope.loadBalancers = getLoadBalancerNames(backingData.loadBalancers);%0A
     
@@ -5836,32 +5836,34 @@
 spaceUpdated();%0A
+  
       %7D);%0A    %7D;
@@ -5935,24 +5935,173 @@
 oupNames();%0A
+      loadBalancerReader.listLoadBalancers('kubernetes')%0A        .then(loadBalancers =%3E $scope.loadBalancers = getLoadBalancerNames(loadBalancers));%0A
       ctrl.u

Update load balancer list when change Namespace (#3482)