'use strict';

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

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

module.factory('OfflineReminderService', function ($q, OfflineRemoteService) {

  var clientIdXiaomiCache;
  var clientIdGetuiCache;
  var clientIdHuaweiCache;
  var service = {
    sendClientId: sendClientId,
    getClientIdGetui: getClientIdGetui,
    getClientIdXiaomi: getClientIdXiaomi,
    getClientIdHuawei: getClientIdHuawei,
  };

  /**
 * 创建失败重新执行的函数。
 *
 * @param {Function} action 执行方法
 * @param {number} delay 延迟时间
 * @param {number} retryNum 最大执行次数，默认为4
 * @returns {Promise}
 */
  function createRetryPromiseFn(action, delay, retryNum) {
    retryNum = retryNum || 4;
    return function retryAction() {
      var args = arguments;
      var defer = $q.defer();
      var count = 0;

      function execAsyncAction() {
        action.apply(action, args).then(function (value) {
          defer.resolve(value);
        }, function () {
          if (count++ > retryNum) {
            defer.resolve('');
          } else {
            setTimeout(execAsyncAction, delay);
          }
        });
      }
      execAsyncAction();
      return defer.promise;
    }
  }


  var getClientIdGetuiWithRetryFeature = createRetryPromiseFn(getClientIdGetui, 2000);
  var getClientIdXiaomiWithRetryFeature = createRetryPromiseFn(getClientIdXiaomi, 2000);
  var getClientIdHuaweiWithRetryFeature = createRetryPromiseFn(getClientIdHuawei, 2000);

  function sendClientId() {
    var devSn = window.device.uuid,
      manufacturer = window.device.manufacturer,
      clientIdXiaomiPromise = getClientIdXiaomiWithRetryFeature(),
      clientIdGetuiPromise = getClientIdGetuiWithRetryFeature(),
      clientIdHuaweiPromise = getClientIdHuaweiWithRetryFeature();

    $q.all([clientIdXiaomiPromise, clientIdGetuiPromise, clientIdHuaweiPromise]).then(function (values) {
      return values;
    }).then(function (result) {
      var clientIdXiaomi = result[0].clientId,
        clientIdGetui = result[1].clientId,
        clientIdHuawei = result[2].clientId;
      return createRetryPromiseFn(function() {
        return OfflineRemoteService.sendReminder(devSn, manufacturer, clientIdXiaomi, clientIdGetui, clientIdHuawei);
      }, 2000, 10)();
    }).then(function() {
      console.log('注册离线消息通道id与设备id的关联关系成功。');
    }, function(error) {
      console.error('注册离线消息通道id与设备id的关联关系成功。', error);
    });
  }

  /**
   * 获取小米SDK的clientId
   */
  function getClientIdXiaomi() {
    var deferred = $q.defer();
    if (window.SinoNetwork && window.SinoNetwork.getXiaoMiClientId) {
      window.SinoNetwork.getXiaoMiClientId(function (data) {
        if (data && data.clientId) {
          deferred.resolve(data);
          clientIdXiaomiCache = data.clientId;
        } else {
          deferred.reject(new Error('获取小米clientId失败'));
        }
      },function(error) {
        deferred.reject(error);
      });
    } else {
      deferred.resolve({
        clientId: ''
      });
    }
    return deferred.promise;
  }

  /**
   * 获取个推SDK的clientId
   */
  function getClientIdGetui() {
    var deferred = $q.defer();
    if (window.SinoNetwork && window.SinoNetwork.getGeTuiClientId) {
      window.SinoNetwork.getGeTuiClientId(function (data) {
        if (data && data.clientId) {
          deferred.resolve(data);
          clientIdGetuiCache = data.clientId;
        } else {
          deferred.reject(new Error('获取个推clientId失败'));
        }
      },function(error) {
        deferred.reject(error);
      });
    } else {
      deferred.resolve({
        clientId: ''
      });
    }
    return deferred.promise;
  }
  /**
   * 获取华为SDK的clientId
   * 
   * @returns
   */

  function getClientIdHuawei() {
    var deferred = $q.defer();
    if (window.SinoNetwork && window.SinoNetwork.getHuaWeiClientId) {
      window.SinoNetwork.getHuaWeiClientId(function (data) {
        if (data && data.clientId) {
          deferred.resolve(data);
          clientIdHuaweiCache = data.clientId;
        } else {
          deferred.reject(new Error('获取华为clientId失败'));
        }
      },function(error) {
        deferred.reject(error);
      });
    } else {
      deferred.resolve({
        clientId: ''
      });
    }
    return deferred.promise;
  }
  return service;
});