'use strict';

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

angular
  .module('intro.services')
  .factory('introService', introService);

/** @ngInject */
function introService(CacheService) {
  var CACHE_KEY = 'intro_notice_log';

  var intro = introJs();
  var options = [];

  var introService = {
    start: start,
    setOptions: setOptions,
    refresh: refresh,
    reset: reset,
    getOption: getOption
  };

  return introService;

  function start(name) {

    var introLog = getLog();
    if (introLog[name]) {
      return;
    }

    var option = getOption(name);

    if (option) {
       log(name);
       intro.setOptions(applyDefaultOption(option));
       intro.start();
    }
  }

  /**
   * 获取具体的配置项
   */
  function getOption(name) {
    for (var i = 0, size = options.length; i < size; i++) {
      var option = options[i];
      if (option.name === name) {
        return option.option;
      }
    }
  }

  function applyDefaultOption(source) {
    var dest = {
      nextLabel: '下一步',
      prevLabel: '上一步',
      skipLabel: '跳过',
      doneLabel: '结束',
      showProgress: false,
      showStepNumbers: false
    }
    _.apply(dest, source);
    return dest;
  }

  function setOptions(_options) {
    options = _options;
  }

  function refresh() {
    intro.refresh();
  }

  /**
   * 重置状态
   */
  function reset() {
    CacheService.remove(CACHE_KEY);
  }

  function log(name) {
    var introLog = CacheService.get(CACHE_KEY, {});
    introLog[name] = true;
    CacheService.put(CACHE_KEY, introLog);
  }

  function getLog() {
    return CacheService.get(CACHE_KEY, {});
  }
}
