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

module.directive('sinoDateInput', function() {
  var shortDateTimePatternRegexp = /^\d{4}-\d{1,2}-\d{1,2}T\d{1,2}:\d{1,2}$/;
  var shortTimePatternRegexp = /^\d{1,2}:\d{1,2}$/;
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModelCtrl) {
      var inputType = attrs.type;
      var isDateTime = inputType === 'datetime' || inputType === 'datetime-local';
      var isTime = inputType === 'time';
      var isoPattern = isDateTime?'Y-m-dTH:i:s' : isTime?'H:i:s' : 'Y-m-d';
      var pattern = isDateTime? 'Y-m-d H:i:s' : isTime?'H:i:s' : 'Y-m-d';

      //DOM value -> Model Value
      ngModelCtrl.$parsers = [function(value) {
        if (value && value instanceof Date) {
          return _.formatDate(value, pattern);
        } else if (value && isDateTime) {
          if (shortDateTimePatternRegexp.test(value)) {
            value += ':00';
          }
          return _.formatDate(_.parseDate(value, isoPattern), pattern);
        } else if (value && isTime) {
          if (shortTimePatternRegexp.test(value)) {
            value += ':00';
          }
          return value;
        } else {
          return value;
        }
      }];

      //Model value -> DOM value
      ngModelCtrl.$formatters = [function(value) {
        if (value && value instanceof Date) {
          return _.formatDate(value, isoPattern);
        } else if (value && isDateTime) {
          return _.formatDate(_.parseDate(value, pattern), isoPattern);
        } else {
          return value;
        }
      }];
    }
  };
});
