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

var module = angular.module('commons.services.configService');

function filterConfigForPlatform(configs) {
  var currentPlatform = ionic.Platform.platform();
  var currentPlatformVersion = parseInt(ionic.Platform.version());
  var platform = currentPlatform + currentPlatformVersion;
  var result = [];
  var resultCache = {};

  for (var i = 0; i < configs.length; i++) {
    var config = configs[i];
    if (config.platform && config.platform.indexOf(platform) >= 0) {
      resultCache[config.platformCategory] = config;
    } else if (config.platformCategory && !config.platform && !resultCache[config.platformCategory]) {
      resultCache[config.platformCategory] = config;
    }
  }

  for (var i = 0; i < configs.length; i++) {
    var config = configs[i];
    if (config.platformCategory && resultCache[config.platformCategory]) {
      result.push(resultCache[config.platformCategory]);
      delete resultCache[config.platformCategory];
    } else if (!config.platformCategory) {
      result.push(config);
    }
  }

  return result;
}

  module.factory('configService', function($http, $q) {
  var configService = {
    getConfig: function() {
        if (ionic.Platform.isIOS() && window.SinoNetwork && window.SinoNetwork.getConfigs) {
            var deferred = $q.defer();
            window.SinoNetwork.getConfigs(function(configs) {
                deferred.resolve(configs);
            }, function(error) {
                deferred.reject(error);
            });
            return deferred.promise.then(filterConfigForPlatform);
        } else {
            return $http.get('config.json?views').then(function(response) {
                var config = response.data;
                return config;
            }).then(filterConfigForPlatform);
        }
    },

    get: function(serverId) {
      return this.getConfig().then(function(config) {
        var servers = config.filter(function(server) {
          return server.id === serverId
        });
        if (servers && servers.length > 0) {
          return servers[0];
        }
      });
    },

    /** 保存server和vpnServerUrl到手机端插件,并重新获取连接 */
    saveAppConfig: function(data) {
      var deferred = $q.defer();
      if (window.SinoNetwork) {
        window.SinoNetwork.configsave(data, function() {
          deferred.resolve(true);
        }, $q.reject);
      } else {
        deferred.resolve(true);
      }
      return deferred.promise;
    },
  };

  return configService;
});
