'use strict';

var $ = require('jquery');
var textDuration = require('../utils/text-duration');

module.exports = function () {
  return {
    restrict: 'E',
    link: function (scope, element, attrs) {
      if ('undefined' !== typeof attrs.since && !attrs.duration) {
        var ival = since(attrs.since, element);
        $(element).tooltip({title: `Started ${new Date(attrs.since).toLocaleString()}`});
        attrs.$observe('since', function () {
          $(element).tooltip({title: `Started ${new Date(attrs.since).toLocaleString()}`});
          clearInterval(ival);
          ival = since(attrs.since, element);
        });
        return scope.$on('$destroy', function () {
          clearInterval(ival);
        });
      }

      var date;
      if ('undefined' !== typeof attrs.datetime) {
        date = new Date(attrs.datetime);
        $(element).tooltip({title: date.toLocaleString()});
      }

      if ('undefined' !== typeof attrs.duration) {
        attrs.$observe('duration', function () {
          textDuration(attrs.duration, element);
        });
        return textDuration(attrs.duration, element);
      }

      attrs.$observe('datetime', function () {
        date = new Date(attrs.datetime);
        $(element).tooltip({title: date.toLocaleString()});
        $(element).text($.timeago(date));
      });
      // TODO: use moment.js
      $(element).text($.timeago(date));
      setTimeout(function () {
        $(element).timeago();
      }, 0);
    }
  };
};

function since(stamp, el) {
  var then = new Date(stamp).getTime();
  function update() {
    var now = new Date().getTime();
    textDuration(now - then, el, true);
  }
  update();
  return setInterval(update, 500);
}
