/*
 * Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

/**
 * The Ironic Root Application.
 *
 * This module defines dependencies and root routes, but no actual
 * functionality.
 */
angular.module('ironic', ['ui.router', 'ui.bootstrap',
  'ironic.drivers', 'ironic.nodes', 'ironic.ports',
  'ironic.util', 'ironic.api'])
  .config(function($urlRouterProvider, $httpProvider, $stateProvider, $$configurationProvider) {
    'use strict';

    // Default UI route
    $urlRouterProvider.otherwise('/ironic');

    // Enable all of our configuration detection methods
    $$configurationProvider.$enableDefault(true);
    $$configurationProvider.$enableConfigLoad(true);
    $$configurationProvider.$enableLocalStorage(true);

    // Ironic's root state, used to resolve global resources before
    // the application fully initializes.
    $stateProvider
      .state('root', {
        'abstract': true,
        'url': '',
        'templateUrl': 'view/ironic/index.html'
      })
      .state('root.ironic', {
        'url': '/ironic',
        'views': {
          'header': {
            'templateUrl': 'view/ironic/header.html',
            'controller': 'HeaderController as headerCtrl'
          },
          'main': {
            'templateUrl': 'view/ironic/main.html'
          }
        },
        'resolve': {
          'configurations': function($$configuration) {
            return $$configuration.query({}).$promise;
          },
          'currentConfiguration': function($$selectedConfiguration, $q) {
            var deferred = $q.defer();

            var resource = $$selectedConfiguration.get();
            resource.$promise.then(
              function() {
                deferred.resolve(resource);
              },
              function() {
                deferred.reject('no_config');
              });
            return deferred.promise;
          }
        }
      })
      .state('root.config', {
        'url': '/config',
        'views': {
          'main': {
            'templateUrl': 'view/ironic/config.html',
            'controller': 'ConfigurationController as ctrl'
          }
        }
      });
  })
  .run(function($rootScope, $state) {
    'use strict';

    var listener = $rootScope.$on('$stateChangeError',
      function (evt, toState, toParams, fromState, fromParams, reason) {
        if (reason === 'no_config') {
          $state.go('root.config');
        } else {
          $state.go('root.ironic');
        }
      });
    $rootScope.$on('$destroy', listener);
  });

/*
 * Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

/**
 * This controller allows the creation of a new configuration.
 */
angular.module('ironic').controller('ConfigurationAddController',
  function($scope, $state, $location, $$configuration, $modalInstance, configuration) {
    'use strict';
    var vm = this;

    vm.configuration = configuration;
    vm.newConfiguration = {
      'name': '',
      'ironic': {
        'apiRoot': ''
      }
    };

    vm.location = {
      'host': $location.host(),
      'protocol': $location.protocol(),
      'port': $location.port()
    };

    vm.save = function() {
      vm.newConfiguration.id = vm.newConfiguration.name;
      $modalInstance.close(vm.newConfiguration);
    };

    vm.close = function() {
      $modalInstance.dismiss();
    };
  });

/*
 * Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

/**
 * This controller allows the management of all the cloud configuration entries.
 */
angular.module('ironic').controller('ConfigurationController',
  function($state, $location, $$configuration, $$selectedConfiguration, $modal) {
    'use strict';
    var vm = this;

    vm.configurations = [];

    vm.location = {
      'host': $location.host(),
      'protocol': $location.protocol(),
      'port': $location.port()
    };

    function reloadConfigurations () {
      vm.configurations = $$configuration.query({});
    }

    /**
     * Select a single configuration for the current application runtime.
     *
     * @param configuration The configuration to select.
     */
    vm.select = function(configuration) {
      $$selectedConfiguration.set(configuration).$promise.then(
        function() {
          $state.go('root.ironic');
        }
      );
    };

    /**
     * Displays the local configuration add modal.
     */
    vm.add = function() {
      //  var deferred = $q.defer();
      $modal.open({
        'templateUrl': 'view/ironic/config_add.html',
        'controller': 'ConfigurationAddController as ctrl',
        'backdrop': 'static',
        'resolve': {
          'configuration': function() {
            return $$configuration.query({}).$promise;
          }
        }
      }).result.then(
        function(newConfig) {
          $$configuration.create(newConfig).$promise.then(reloadConfigurations);
        });
    };

    vm.remove = function(config) {
      config.$remove().$promise.then(reloadConfigurations);
    };

    reloadConfigurations();
  });

/*
 * Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

/**
 * Controller for our application header.
 */
angular.module('ironic').controller('HeaderController',
  function ($scope, $state, configurations, currentConfiguration, $$selectedConfiguration) {
    'use strict';
    var vm = this;

    vm.configurations = configurations;
    vm.currentConfiguration = currentConfiguration;

    vm.switchCloud = function (cloudConfig) {
      $$selectedConfiguration.set(cloudConfig).$promise.then(
        function() {
          $state.reload();
        });
    };
  });
