var angular = require('angular');
require('../modules');
require('../../../commons/directives/$toast');
require('../services/FavoriteLinkerService');

var module = angular.module('linker.directives');

module.directive('sinoLinkerFavoriteButton', function($toast,
  $rootScope, FavoriteLinkerService) {
  return {
    restrict: 'A',
    scope: {
      userId: '@sinoLinkerFavoriteButton',
      user: '=linkerFavoriteUser'
    },
    link: function(scope, element, attr) {
      var userId = scope.userId,
        favorite = false,
        user = scope.user,
        dealing = false;
      function updateClass() {
        if (favorite) {
          element.removeClass('ion-ios-heart-outline');
          element.addClass('ion-ios-heart');
        } else {
          element.removeClass('ion-ios-heart');
          element.addClass('ion-ios-heart-outline');
        }
      }

      // 监听常用联系人变化
      $rootScope.$on('favoriteUpdate', function() {
        init();
      });

      function init() {
        if (userId) {
          favorite = FavoriteLinkerService.isFavorite(userId);
          updateClass();
        }
      }

      init();

      element.on('click', function() {
        if(dealing) {console.log(111111);return;}
        dealing = true;

        var addFn = !user ? FavoriteLinkerService.add([userId]) : FavoriteLinkerService.add([userId], [user]);
        var promise = favorite? FavoriteLinkerService.remove(userId) : addFn,
          errorMsg = favorite? '删除常用联系人失败' : '添加常用联系人失败';

        promise.then(function() {}, function() {
          $toast.showShortCenter(errorMsg);
        })['finally'](function() {
          dealing = false;
        });
      });
    }
  };
});
