'use strict';

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

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

module.factory('webmailService', function($http, LinkerService, $q, CoreAppConfig, $toast) {
  var webmailService = {};
  var coreMailBaseUrl = null;
  var opened = false;
  var mailType_web = null, mailType_cma = null;

  function toCoreMail(url, title, backTitle) {
    var deferred = $q.defer();
    if (window.SinoNetwork && window.SinoNetwork.toCoreMail) {
      window.SinoNetwork.toCoreMail(url, title, backTitle, deferred.resolve, deferred.resolve);
    } else {
       window.open(url, '_self', 'location=no,closebuttoncaption=Close,enableViewportScale=yes');
       deferred.resolve();
    }
    return deferred.promise;
  }

  function getCoreMailBaseUrl() {
    return coreMailBaseUrl;
  }

  webmailService.setCoreMailBaseUrl = function(_coreMailBaseUrl) {
    if(!_.isEmpty(_coreMailBaseUrl)) {
      coreMailBaseUrl =  _coreMailBaseUrl;
    }
  };

  webmailService.setMailTypeCma = function(_mailType) {
    mailType_cma = _mailType;
  };
  webmailService.setMailTypeWeb = function(_mailType) {
    mailType_web = _mailType;
  };


  webmailService.openWebMail = function(mailType, title, backTitle) {
    var coreMailPublicUrl =  CoreAppConfig.serverUrl + getCoreMailBaseUrl();
      if (opened) { return; }
      opened = true;
      return getEmailLoginInfo(mailType).then(function(data) {
        var sid = data.sid,
          url = coreMailPublicUrl + '?coremail_type=' + mailType;

        if ((mailType === 'web' && sid && data.isEmailName) ||
          (mailType !== 'web' && sid)) {
            url = coreMailPublicUrl + 'main.jsp?coremail_type=' + mailType + '&sid=' + sid;
        }

        return url;
      }).then(function(url) {
          return toCoreMail(url, title, backTitle);
      }, function(error) {
        $toast.showLongBottom('无法访问邮箱服务器，请稍后再试。');
      })['finally'](function() {
          opened = false;
      });
  };

  /**
   * 获取登录邮箱所需的信息
   * sid
   * unreadNumber
   */
  function getEmailLoginInfo(mailType) {
    return $http.get('/webmail?userId=' + LinkerService.currentUserId + '&type=' + mailType, {
      timeout: 15000
    }).then(function(response) {
      return response.data;
    });
  };

  return webmailService;
});
