/* vpn处理service */
'use strict';

var angular = require('angular'),
  _ = require('jsUtil');
require('../modules');
require('../../notice/services/NoticeService');

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

module.factory('VPNManagerService', function($http, LinkerService, NoticeService, $q, $state,
  $rootScope, fileService) {

  /**
  * vpn提醒信息实体，最终回传递发送给通知页面
  *
  * @param {String} moduleName 模块
  * @param {Date} time 创建时期
  * @param {CertInfo} 证书信息
  *   {Date} notBefore 有效期从
  *   {Date} notAfter 有效期到
  *   {String} issuerDN 颁发人
  *   {String} subjectDN 使用者
  * @param {String} status 通知状态
  *   load: 正在下载
  *   create: 第一次安装成功
  * loadError: 下载失败，没有证书或者报错
  *   update: 第一次后需要更新，更新成功
  * notNeedUpdate: 第一次以后不需要更新
  * inValidNotAfter: 没有需要更新证书，并且当前正是已经过期
  */
  function VPNNoticeObject(status, certInfo) {
    certInfo = certInfo ? certInfo : {};
    this.moduleName = 'vpn';
    this.time = new Date();
    this.status = status;
    this.notBefore = certInfo.notBefore;
    this.notAfter = certInfo.notAfter;
    this.issuerDN = certInfo.issuerDN;
    this.subjectDN = certInfo.subjectDN;
  }

  function VPNManagerService() {
  }

  VPNManagerService.prototype.vaildNotAfter = function() {
    this.getCert().then(function(certInfo) { // 获取当前已经安装证书的信息
      if((!_.isEmpty(certInfo) && new Date() >= certInfo.notAfter)) { // 旧证书过期了
          NoticeService.insert(new VPNNoticeObject('inValidNotAfter', certInfo));
      }
      return certInfo;
    });
  };

  /** 更新或者创建一个VPN证书 */
  VPNManagerService.prototype.createOrUpdate = function() {
    // 1、添加正在加载的通知
    NoticeService.insert(new VPNNoticeObject('load'));

    var that = this,
      oldData = {},
      newData = {};
    this.getCert().then(function(certInfo) { // 2、获取当前APP中已经有的证书信息
      oldData = certInfo;
      return oldData;
    }).then(function() {
      return that.download(oldData); // 3、获取最新的需要更新的证书，如果不需要更新的话为null
    }).then(function(data) {
      newData = data;
      return that.install(data);  // 4、安装最新的需要更新的证书
    }).then(function() { // 5、添加通知提醒
      if (!_.isEmpty(newData)) { // 有新证书的情况
        if (new Date() >= newData.certInfo.notAfter) { // 新证书过期了
          NoticeService.insert(new VPNNoticeObject('inValidNotAfter', newData.certInfo));
          return;
        }
        if (!_.isEmpty(oldData)) {
          NoticeService.insert(new VPNNoticeObject('update', newData.certInfo)); // 证书更新
        } else {
          NoticeService.insert(new VPNNoticeObject('create', newData.certInfo)); // 首次安装证书
        }
      } else { // or 没有新证书
        if ((new Date() >= oldData.notAfter) && !_.isEmpty(oldData)) { // 旧证书过期了
          NoticeService.insert(new VPNNoticeObject('inValidNotAfter', oldData)); // 没有更新的证书时间并且过了有效期
        } else if (!_.isEmpty(oldData)) {
          NoticeService.insert(new VPNNoticeObject('notNeedUpdate', oldData)); // 不需要更新证书
        }
      }
    }, function() {
      NoticeService.insert(new VPNNoticeObject('loadError')); // 证书处理错误
    });
  };

  /** 在本地获取证书 */
  VPNManagerService.prototype.getCert = function () {
    var deferred = $q.defer();
    if (!window.SinoNetwork) {
      deferred.resolve(null);
      return deferred.promise;
    }

    window.SinoNetwork.certlist(function (cert) {
      if (cert.data) {
        var certInfos = JSON.parse(cert.data);
        _.each(certInfos, function (certInfo) {
          certInfo.notAfter = new Date(certInfo.notAfter);
          certInfo.notBefore = new Date(certInfo.notBefore);
          certInfo.lastModifiedDate = new Date(certInfo.lastModifiedDate);
        });
        deferred.resolve(certInfos[0]);
      } else {
        deferred.resolve(null);
      }
    }, function (msg) {
      deferred.reject(msg);
    });
    return deferred.promise;
  };

  /** 下载证书信息 */
  VPNManagerService.prototype.download = function (certInfo) {
    certInfo = certInfo ? certInfo : {};
    return this.getCertContentAndPassword().then(function (values) {
      return $http.post('/vpn/manager/download/newest', {
          certContent: values[0],
          certPassword: values[1],
          lastModifiedDate: certInfo.lastModifiedDate
      });
    }).then(function (response) {
      return response.data;
    });
  };

  VPNManagerService.prototype.getCertContentAndPassword = function () {
    if (window.cordova) {
      var p12FilePath = cordova.file.dataDirectory + 'cert/current.p12',
      passwordFilePath = cordova.file.dataDirectory + 'cert/current.p12.password';
      return $q.all([
        fileService.readAsText(p12FilePath),
        fileService.readAsText(passwordFilePath)
      ]).then(function (contents) {
        return contents;
      }, function () {
        return $q.all(['','']);
      });
    } else {
      return $q.all(['','']);
    }
  };

  /** 安装证书到本地 */
  VPNManagerService.prototype.install = function (data) {
    var deferred = $q.defer();
    if (window.SinoNetwork && data) {
      window.SinoNetwork.certsave(data.certContent, data.certPassword,
        data.md5Value, function(cert) {
         if (cert.data) {
           var certInfos = JSON.parse(cert.data);
           if (_.isEmpty(certInfos)) {
             deferred.resolve(null);
           }
           var certInfo = certInfos[0];
           return $http.post('/vpn/manager/update/lastModifiedDate', {
             id: data.id,
             lastModifiedDate: new Date(certInfo.lastModifiedDate)
           }).then(function() {
             deferred.resolve(data);
           }, deferred.reject);
         } else {
           deferred.resolve(null);
         }
      }, deferred.reject);
    } else {
      deferred.resolve(data);
    }
    return deferred.promise;
  };

  return VPNManagerService;
});

