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

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

module.run(function(AudioPlayerService) {
  AudioPlayerService.loadFromCache();
});

module.factory('AudioPlayerService', function(localforage) {
  var flagMap = {},
    playingAudio = {},
    totalFlagMap = {},
    fileEntryMap = {},
    promiseMap = {},
    loginUserId,
    key = 'audioPlayFlagMap';

  function addPlayingAudio(id, fn) {
    playingAudio[id] = fn;
  }

  function removePlayingAudio(id) {
    delete playingAudio[id];
  }

  function setLoginUserId(userId) {
    loginUserId = userId;
  }

  function addFileEntry(key, value) {
    fileEntryMap.key = value;
  }

  function getFileEntry(key) {
    return fileEntryMap[key];
  }

  function addPromise(key, promise) {
    promiseMap.key = promise;
  }

  function getPromise(key) {
    return promiseMap[key];
  }

  function removePromise(key) {
    delete promiseMap[key];
  }

  function setRead(id) {
    flagMap[id] = true;
    sync();
  }

  function getRead(id) {
    return flagMap[id];
  }

  function loadFromCache() {
    localforage.getItem(key).then(function(map) {
      if (map) {
        totalFlagMap = map;
        flagMap = totalFlagMap[loginUserId] || {};
      }
    });
  }

  function sync() {
    totalFlagMap[loginUserId] = flagMap;
    return localforage.setItem(key, totalFlagMap);
  }
  /**
   * 播放下一个语音
   * @param  {DOM} finder 基准节点。
   */
  function playNext(finder, getNextProbleAudioFn) {
    var player, playerElement;
    while (finder.nextElementSibling) {
      player = getNextProbleAudioFn(finder);
      if (player) {
        playerElement = angular.element(player);
        break;
      }
      finder = finder.nextElementSibling;
    }
    if(playerElement) {
      playerElement.triggerHandler('click');
    }
  }

  function stopPlayingAudio() {
    var stopPlayFn;
    for (var id in playingAudio) {
      stopPlayFn = playingAudio[id]();
      stopPlayFn();
    }
  }

  return {
    setRead: setRead,
    getRead: getRead,
    addPlayingAudio: addPlayingAudio,
    removePlayingAudio: removePlayingAudio,
    stopPlayingAudio: stopPlayingAudio,
    addFileEntry: addFileEntry,
    getFileEntry: getFileEntry,
    addPromise: addPromise,
    getPromise: getPromise,
    removePromise: removePromise,
    loadFromCache: loadFromCache,
    setLoginUserId: setLoginUserId,
    sync: sync,
    playNext: playNext
  };
});
