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

module.filter('sinoDateIncrease', function() {
  var pattern = /([+-])?(\d{1,})([dmy])/;
  var defaultFormat = 'Y-m-d';
  function parseInscreaseExp(exp) {
    var components = exp.match(pattern),
      isAdd = components[1] != '-',
      num = parseInt(components[2]),
      unit = components[3];
    return {
      factor: isAdd? 1 : -1,
      num: num,
      unit: unit
    };
  }

  function getIncreaseWithMilliseconds(increase) {
    var unit = increase.unit,
      num = increase.num,
      result = 0;
    switch(unit) {
      case 'd':
        result = num * 24 * 3600 * 1000;
        break;
      case 'm':
        result = num * 30 * 24 * 3600 * 1000;
        break;
      case 'y':
        result = num * 365 * 24 * 3600 * 1000;
        break;
    }
    return result;
  }

  return function(value, increaseExp, format) {
    format = format || defaultFormat;
    var value = value && _.isString(value)? _.parseDate(value, format) : value;
    if (value instanceof Date && increaseExp) {
      var increase = parseInscreaseExp(increaseExp),
        milliseconds = getIncreaseWithMilliseconds(increase),
        result = value.getTime() + (milliseconds * (increase.factor));
      return new Date(result);
    } else {
      return value;
    }
  };
});
