/**
 * Author: Andrew Martlew <a.martlew at library.uq.edu.au>
 * Date: 14/05/13
 *
 * Membership app settings controller
 */

'use strict';

angular.module('uql.membership')
  .controller('MembershipSettingsCtrl', ['$scope', '$log', '$rootScope', '$location', '$window', 'AccountSvc',
    'MembershipSvc',
    function ($scope, $log, $rootScope, $location, $window, AccountSvc, MembershipSvc) {

      $scope.user = {};
      $scope.accountSvc = AccountSvc;
      $scope.membershipSvc = MembershipSvc;
      $scope.list = [];
      $scope.expiries = [];
      $scope.formData = {};
      $scope.form = {};

      /**
       * @description Updates the default expiry on a type
       * @param {Object} type
       * @param {String} control
       */
      $scope.updateGlobal = function () {
        $scope.form._updating = true;
        var type = {
          'expiry': $scope.form.defaultExpiry,
          'value': 'global'
        };
        $scope.membershipSvc.updateType(type)
        .then(function () {
          // Success
        }, function () {
          // Error
        })
        .finally(function () {
          $scope.form._updating = false;
        });
      };

      /**
       * @description Updates the default expiry on a type
       * @param {Object} type
       * @param {String} control
       */
      $scope.update = function (type) {
        type._updating = true;
        $scope.membershipSvc.updateType(type)
        .finally(function () {
          type._updating = false;
        });
      };

      /**
       * @description Navigates to the admin page
       */
      $scope.goAdmin = function () {
        $location.path('membership/admin');
      };

      /**
       * @description Initialises the controller
       */
      $scope.init = function () {
        $scope.accountSvc.getAccount().then(function (user) {
          $scope.user = user;

          if ($scope.user.hasOwnProperty('hasSession') && $scope.user.hasSession) {

            $scope.membershipSvc.get()
            .then(function (data) {
              $scope.formData = data;
              $scope.list = $scope.formData.account_types;

              $scope.membershipSvc.getTypes()
              .then(function (data) {
                var expiries = [];
                for (var m = 0; m < data.length; m++) {
                  expiries[data[m].name] = data[m].expiry;
                  if (data[m].name === 'global') {
                    $scope.form.defaultExpiry = data[m].expiry;
                  }
                }
                for (var n = 0; n < $scope.list.length; n++) {
                  $scope.list[n].expiry = expiries[$scope.list[n].value];
                }
              }, function () {
              });
            }, function () {
            });
          } else {
            $rootScope.$broadcast('uql.account.login');
          }
        }, function () {
          $rootScope.$broadcast('uql.account.login');
        });
      };

      $scope.init();
    }]);
