'use strict';

var angular = require('angular');
require('../modules');

var module = angular.module('initializeset.services');

module.factory('SetUrlService', function($state, $q, configService, $rootScope, CoreAppConfig) {
  var _nextAction;
  var InitializeSetUrlService = {
    setLoginUrl: function(nextAction) {
      _nextAction = nextAction;
      if (window.localStorage.passSetUrl === 'true') {
        var serverId = CoreAppConfig.applicationConfig.getServerId();
        configService.get(serverId).then(function(data) {
          if (data) {
            return InitializeSetUrlService.saveConfig(data);
          } else {
            throw new Error('无法获取到配置数据');
          }
        }).then(function() {
          InitializeSetUrlService.goNext();
        }, function() {
          $state.go('initializeset-setUrl');
        });
      } else {
        configService.getConfig().then(function(config) {
          if (config.length === 1) {
            InitializeSetUrlService.saveConfig(config[0]);
            InitializeSetUrlService.goNext();
          } else  {
            $state.go('initializeset-setUrl');
          }
        });
      }
    },

    saveConfig: function(data) {
      return $q.all([CoreAppConfig.updateConfig(data), configService.saveAppConfig(data)]);
    },

    goNext: function() {
      if (!window.SinoNetwork) {
        $rootScope.$broadcast('server.online');
      }
      window.localStorage.passSetUrl = 'true';
      _nextAction();
    }
  };

  return InitializeSetUrlService;
});


