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

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

module.factory('sinoNetwork', function($q) {

  function toJSON(data) {
    if (_.isString(data)) {
      return JSON.parse(data);
    } else {
      return data;
    }
  }
  var sinoNetwork = {

    hasCert: function() {
      var deferred = $q.defer();
      if (window.SinoNetwork) {
        window.SinoNetwork.certlist(function(cert) {
          if (cert && !_.isEmpty(toJSON(cert.data))) {
            deferred.resolve(true);
          } else {
            deferred.resolve(false);
          }
        }, deferred.reject);
      } else {
        deferred.resolve(true);
      }
      return deferred.promise;
    },

    getCACert: function() {
      var deferred = $q.defer();
      if (window.SinoNetwork) {
        window.SinoNetwork.getCACert(function(ca) {
          deferred.resolve(ca);
        });
      } else {
        deferred.resolve({});
      }
      return deferred.promise;
    },

    hasCACert: function() {
      return this.getCACert().then(function(value) {
        if (!_.isEmpty(value) && !_.isEmpty(value.cert)) {
          return true;
        } else {
          return false;
        }
      });
    },

    versionUpdate: function() {
      var deferred = $q.defer();
      if (window.SinoNetwork) {
        window.SinoNetwork.versionUpdate(function() {
          deferred.resolve(true);
        }, deferred.reject);
      } else {
        deferred.resolve(false);
      }
      return deferred.promise;
    },

    getAppVersion: function() {
      var deferred = $q.defer();
      if (window.SinoNetwork && window.SinoNetwork.getAppVersion) {
        window.SinoNetwork.getAppVersion(function(data) {
          deferred.resolve(data);
        }, deferred.reject);
      } else {
        deferred.resolve({
          needUpdate: false
        });
      }
      return deferred.promise;
    },

    startAppInit: function() {
      var deferred = $q.defer();
      if (window.SinoNetwork && window.SinoNetwork.startAppInit) {
        window.SinoNetwork.startAppInit(function() {
          deferred.resolve(true);
        }, deferred.reject);
      } else {
        deferred.resolve(true);
      }
    },

    stopAppInit: function() {
      var deferred = $q.defer();
      if (window.SinoNetwork && window.SinoNetwork.stopAppInit) {
        window.SinoNetwork.stopAppInit(function() {
          deferred.resolve(true);
        }, deferred.reject);
      } else {
        deferred.resolve(true);
      }
    }
  };

  return sinoNetwork;
});
