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

/**
 * 信息发布Detail页面 缓存服务
 */
var module = angular.module('info.directives');

function getWidth(element, elementCss) {
  var container = element,
    table = element.children[0],
    parent = element.parentElement;
  if(table.width) {
    return table.width;
  } else {
    var parentWidth = parent.clientWidth;
    var tableWidth = table.clientWidth;
    if (Math.abs(parentWidth - tableWidth) < 2) {
      return parentWidth;
    } else {
      return tableWidth;
    }
  }
}

module.directive('setTableWidth', function($timeout) {
  return {
    restrict: 'C',
    link: function(scope, element, attrs) {
      var promise = $timeout(function() {
        var outlineCss = document.defaultView.getComputedStyle(element[0], null),
          width = getWidth(element[0], outlineCss);
        if(width > 0) {
          element[0].style.width = width + 'px';
        }

      }, 0);

      scope.$on('$destroy', function() {
        $timeout.cancel(promise);
      });
    }
  };
});
