var angular = require('angular'),
 _ = require('jsUtil');

 require('../modules');

angular
  .module('commons.services.authVisibleService')
  .factory('AppModulesAuthVisibleService', AppModulesAuthVisibleService);

/* @ngInject*/
function AppModulesAuthVisibleService($http) {
  var storageKey = 'sino_appmodules_authvisible1';
  var watchers = [];
  var service = {
      fetch: fetch,
      clear: clear,
      get: getAuthorityFromCache
  };

  function fetchAuthority(moduleIds, appTypeName) {
    var authorityUrl = '/authority?models='+ moduleIds.join(',') + '&type=' + appTypeName;

    return $http.get(authorityUrl)
      .then(function(response) {
        return response.data;
      });
  }

  /**
   * 更新权限
   */
  function fetch(moduleIds, appTypeName) {
    return fetchAuthority(moduleIds, appTypeName)
      .then(function(authority) {
        window.localStorage.setItem(storageKey, JSON.stringify(authority));
        return authority;
      });
  }

  function getAuthorityFromCache() {
    var _auth = window.localStorage.getItem(storageKey);
    try {
      var authorityMap = _.isEmpty(_auth) ? null : JSON.parse(_auth);
      if (authorityMap && typeof authorityMap === 'object') {
        return authorityMap;
      } else {
        return null;
      }
    } catch (e) {
      return null;
    }
  }

  function clear() {
    window.localStorage.removeItem(storageKey);
  }

  return service;
}
