var angular = require('angular');
require('../modules');
require('../services/PersonImgCache');
var module = angular.module('linker.directives');

module.directive('sinoPersonPhoto', function(CoreAppConfig, PersonImgCache) {
  function applyImageSize(element, size) {
    if (size) {
      element.classList && element.classList.add('size_' + size);
    }
    element.classList && element.classList.add('item-image');
  }

  function calcRealSize(size) {
    var width = size.split('x')[0],
      height = size.split('x')[1],
      ratio = Math.max(1, window.devicePixelRatio);
    return (width * ratio) + 'x' + (height * ratio);
  }

  return {
    template: '<img></img>',
    restrict: 'E',
    scope: true,
    link: function(scope, element, $attrs) {
      var size = $attrs['size'] || '40x40',
        photoSize = calcRealSize(size),
        loaded = false,
        img = element[0].firstElementChild;

      applyImageSize(element[0], size);

      $attrs.$observe('userId', function(userId) {
        blankImg();
        if (userId === '1') {
          return;
        }
        if (userId) {
          PersonImgCache.listen(userId, showPersonImg);
          showPersonImg(PersonImgCache.getPersonImgUrl(userId));
        }
      });

      /**
       * 展现用户图像
       * @param {String} url 用户图像链接
       */
      function showPersonImg(url) {
        if(url) {
          loaded = false;
          img.src = CoreAppConfig.serverUrl + '/base-user/user/photo/' + url + '_' + photoSize + '?restrictRatio=true&ratio=1.0';
        } else {
          blankImg();
        }
      }

      /**
       * 清空用户图像
       */
      function blankImg() {
        if(img.src.indexOf('data') === 0) {
          return;
        }
         img.width = 1;
         img.height = 1;
         img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=';
      }

      img.onerror = function() {
        if (!loaded) {
          loaded = true;
          blankImg();
        }
      };
    }
  };
});
