var angular = require('angular');
var _ = require('jsUtil');
require('../modules');
var module = angular.module('flowmodulebase.directives');

module.directive('sinoDateRange', function($parse) {
  var dateFormat = "Y-m-d";
  var DAY_MS = 24 * 3600 * 1000;
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var setter = $parse(attrs.sinoDateRange).assign;
      function updateValue() {
        if (attrs.start && attrs.end) {
          var days = calDays(attrs.start, attrs.end);
          setter(scope, days);
        }
      }

      function calDays(start, end) {
        start = _.parseDate(start, dateFormat).getTime();
        end = _.parseDate(end, dateFormat).getTime();
        var days = (end - start) / DAY_MS;
        return days + 1;
      }

      attrs.$observe('start', updateValue);
      attrs.$observe('end', updateValue);
    }
  }
});
