'use strict';

var angular = require('angular');
require('jsUtil');
require('../modules');
require('./InfoRemoteService');
require('./InfoRepository');

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

module.factory('InfosService', function($q, InfoRemoteService, InfoRepository) {
  var service = {};
  /**
   * More页面列表
   * v3
   * @param  {[type]} modlId 模块id
   * @param  {[type]} pageNo 分页页码
   * @return {[type]}        得到的数据
   */
  service.getInfos = function(mode, modlId, pageNo, listUrl) {
    var deferred = $q.defer();

    InfoRemoteService.queryInfos(mode, modlId, pageNo, listUrl).then(function(data) {
      deferred.resolve(data);
    }, function() {//连接失败
      deferred.reject(false);
    });

    return deferred.promise;
  };

  /**
   * v4
   */
  service.getInfoList = function(mode, modlId, pageNo, listUrl, md5) {
    var deferred = $q.defer();
    InfoRemoteService.queryInfoList(mode, modlId, pageNo, listUrl, md5).then(function(data) {
      deferred.resolve(data);
    }, function() {//连接失败
      deferred.reject(false);
    });

    return deferred.promise;
  };

  function replace(oldInfo, info) {
    if(_.isEmpty(oldInfo)) {
      oldInfo = info;
    } else {
      for (var infoId in info) {
        oldInfo[infoId] = info[infoId];
      }
    }

  }

  function syncinfo(info, modlId, infoId) {
    var md5 = InfoRepository.getMd5() || '-1';

    InfoRemoteService.queryInfo(modlId, infoId, md5).then(function(data) {
      if(!_.isNull (data.md5)) {//服务器-->缓存
        InfoRepository.addOrUpdateInfo(infoId, data, data.md5);
        replace(info, data);
      }
    });
  }
  /**
   * 获取一条信息的详情
   * @param  {[type]} modlId 模块id
   * @param  {[type]} infoId 信息id
   * @return {[type]}        查询到的数据信息
   */
  service.getDetailInfo = function(modlId, infoId) {
    var info = InfoRepository.getInfo(infoId);
    var md5 = InfoRepository.getMd5() || '-1';
    if(_.isEmpty(info)) {//缓存中没有数据
      return InfoRemoteService.queryInfo(modlId, infoId, md5).then(function(data) {
        if(!_.isNull (data.md5) && !_.isEmpty(data)) {//服务器-->缓存
          InfoRepository.addOrUpdateInfo(infoId, data, data.md5);
          replace(info, data);
        }
        return data;
      });
    }else {
      syncinfo(info, modlId, infoId);//更新数据
      return $q.when(info);
    }

  };
  service.inNotion = function(modlId, infoId) {
    InfoRemoteService.updateNotion(modlId, infoId);
  }

  return service;
});
