var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g;
var twoDigits = '\\d\\d?';
var threeDigits = '\\d{3}';
var fourDigits = '\\d{4}';
var word = '[^\\s]+';
var literal = /\[([^]*?)\]/gm;
var noop = function () { };
var dayNames = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday',
];
var monthNames = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December',
];
var monthNamesShort = shorten(monthNames, 3);
var dayNamesShort = shorten(dayNames, 3);
export var i18n = {
    dayNamesShort: dayNamesShort,
    dayNames: dayNames,
    monthNamesShort: monthNamesShort,
    monthNames: monthNames,
    amPm: ['am', 'pm'],
    DoFn: function DoFn(D) {
        return (D +
            ['th', 'st', 'nd', 'rd'][D % 10 > 3 ? 0 : ((D - (D % 10) !== 10 ? 1 : 0) * D) % 10]);
    },
};
export var masks = {
    default: 'ddd MMM DD YYYY HH:mm:ss',
    shortDate: 'M/D/YY',
    mediumDate: 'MMM D, YYYY',
    longDate: 'MMMM D, YYYY',
    fullDate: 'dddd, MMMM D, YYYY',
    shortTime: 'HH:mm',
    mediumTime: 'HH:mm:ss',
    longTime: 'HH:mm:ss.SSS',
};
var formatFlags = {
    D: function (dateObj) {
        return String(dateObj.getDate());
    },
    DD: function (dateObj) {
        return pad(dateObj.getDate());
    },
    Do: function (dateObj, i18n) {
        return i18n.DoFn(dateObj.getDate());
    },
    d: function (dateObj) {
        return String(dateObj.getDay());
    },
    dd: function (dateObj) {
        return pad(dateObj.getDay());
    },
    ddd: function (dateObj, i18n) {
        return i18n.dayNamesShort[dateObj.getDay()];
    },
    dddd: function (dateObj, i18n) {
        return i18n.dayNames[dateObj.getDay()];
    },
    M: function (dateObj) {
        return String(dateObj.getMonth() + 1);
    },
    MM: function (dateObj) {
        return pad(dateObj.getMonth() + 1);
    },
    MMM: function (dateObj, i18n) {
        return i18n.monthNamesShort[dateObj.getMonth()];
    },
    MMMM: function (dateObj, i18n) {
        return i18n.monthNames[dateObj.getMonth()];
    },
    YY: function (dateObj) {
        return pad(String(dateObj.getFullYear()), 4).substr(2);
    },
    YYYY: function (dateObj) {
        return pad(dateObj.getFullYear(), 4);
    },
    h: function (dateObj) {
        return String(dateObj.getHours() % 12 || 12);
    },
    hh: function (dateObj) {
        return pad(dateObj.getHours() % 12 || 12);
    },
    H: function (dateObj) {
        return String(dateObj.getHours());
    },
    HH: function (dateObj) {
        return pad(dateObj.getHours());
    },
    m: function (dateObj) {
        return String(dateObj.getMinutes());
    },
    mm: function (dateObj) {
        return pad(dateObj.getMinutes());
    },
    s: function (dateObj) {
        return String(dateObj.getSeconds());
    },
    ss: function (dateObj) {
        return pad(dateObj.getSeconds());
    },
    S: function (dateObj) {
        return String(Math.round(dateObj.getMilliseconds() / 100));
    },
    SS: function (dateObj) {
        return pad(Math.round(dateObj.getMilliseconds() / 10), 2);
    },
    SSS: function (dateObj) {
        return pad(dateObj.getMilliseconds(), 3);
    },
    a: function (dateObj, i18n) {
        return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1];
    },
    A: function (dateObj, i18n) {
        return dateObj.getHours() < 12
            ? i18n.amPm[0].toUpperCase()
            : i18n.amPm[1].toUpperCase();
    },
    ZZ: function (dateObj) {
        var o = dateObj.getTimezoneOffset();
        return ((o > 0 ? '-' : '+') +
            pad(Math.floor(Math.abs(o) / 60) * 100 + (Math.abs(o) % 60), 4));
    },
};
var parseFlags = {
    D: [twoDigits, setDay],
    DD: [twoDigits, setDay],
    Do: [twoDigits + word, setDay],
    M: [twoDigits, setMonth],
    MM: [twoDigits, setMonth],
    YY: [
        twoDigits,
        function (d, v) {
            var y = parseInt(v, 10);
            var da = new Date();
            var cent = parseInt(String(da.getFullYear()).substr(0, 2), 10);
            var year = String(y > 68 ? cent - 1 : cent) + v;
            d.year = parseInt(year, 10);
        },
    ],
    h: [twoDigits, setHour],
    hh: [twoDigits, setHour],
    H: [twoDigits, setHour],
    HH: [twoDigits, setHour],
    m: [twoDigits, setMinute],
    mm: [twoDigits, setMinute],
    s: [twoDigits, setSecond],
    ss: [twoDigits, setSecond],
    YYYY: [
        fourDigits,
        function (d, v) {
            d.year = parseInt(v, 10);
        },
    ],
    S: [
        '\\d',
        function (d, v) {
            d.millisecond = parseInt(v, 10) * 100;
        },
    ],
    SS: [
        '\\d{2}',
        function (d, v) {
            d.millisecond = parseInt(v, 10) * 10;
        },
    ],
    SSS: [
        threeDigits,
        function (d, v) {
            d.millisecond = parseInt(v, 10);
        },
    ],
    d: [twoDigits, noop],
    dd: [twoDigits, noop],
    ddd: [word, noop],
    dddd: [word, noop],
    MMM: [word, monthUpdate('monthNamesShort')],
    MMMM: [word, monthUpdate('monthNames')],
    a: [word, setPm],
    A: [word, setPm],
    ZZ: [
        '[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z',
        function (d, v) {
            var parts = (v + '').match(/([+-]|\d\d)/gi);
            var minutes;
            if (parts) {
                minutes = parseInt(parts[1], 10) * 60 + parseInt(parts[2], 10);
                d.timezoneOffset = parts[0] === '+' ? minutes : -minutes;
            }
        },
    ],
};
export function format(dateObj, mask, i18nSettings) {
    if (i18nSettings === void 0) { i18nSettings = i18n; }
    if (typeof dateObj === 'number') {
        dateObj = new Date(dateObj);
    }
    if (Object.prototype.toString.call(dateObj) !== '[object Date]' ||
        isNaN(dateObj.getTime())) {
        throw new Error('Invalid Date in fecha.format');
    }
    mask = masks[mask] || mask || masks['default'];
    var literals = [];
    mask = mask.replace(literal, function ($0, $1) {
        literals.push($1);
        return '@@@';
    });
    mask = mask.replace(token, function ($0) {
        return $0 in formatFlags
            ? formatFlags[$0](dateObj, i18nSettings)
            : $0.slice(1, $0.length - 1);
    });
    return mask.replace(/@@@/g, function () {
        return literals.shift();
    });
}
export function parse(dateStr, format, i18nSettings) {
    if (i18nSettings === void 0) { i18nSettings = i18n; }
    if (typeof format !== 'string') {
        throw new Error('Invalid format in fecha.parse');
    }
    format = masks[format] || format;
    if (dateStr.length > 1000) {
        return null;
    }
    var dateInfo = {};
    var parseInfo = [];
    var literals = [];
    format = format.replace(literal, function ($0, $1) {
        literals.push($1);
        return '@@@';
    });
    var newFormat = regexEscape(format).replace(token, function ($0) {
        if (parseFlags[$0]) {
            var info = parseFlags[$0];
            parseInfo.push(info[1]);
            return '(' + info[0] + ')';
        }
        return $0;
    });
    newFormat = newFormat.replace(/@@@/g, function () {
        return literals.shift();
    });
    var matches = new RegExp(newFormat, 'i').exec(dateStr);
    if (!matches) {
        return null;
    }
    for (var i = 1; i < matches.length; i++) {
        parseInfo[i - 1](dateInfo, matches[i], i18nSettings);
    }
    var today = new Date();
    if (dateInfo.isPm === true &&
        dateInfo.hour != null &&
        +dateInfo.hour !== 12) {
        dateInfo.hour = +dateInfo.hour + 12;
    }
    else if (dateInfo.isPm === false && +dateInfo.hour === 12) {
        dateInfo.hour = 0;
    }
    var date;
    if (dateInfo.timezoneOffset != null) {
        dateInfo.minute = +(dateInfo.minute || 0) - +dateInfo.timezoneOffset;
        date = new Date(Date.UTC(dateInfo.year || today.getFullYear(), dateInfo.month || 0, dateInfo.day || 1, dateInfo.hour || 0, dateInfo.minute || 0, dateInfo.second || 0, dateInfo.millisecond || 0));
    }
    else {
        date = new Date(dateInfo.year || today.getFullYear(), dateInfo.month || 0, dateInfo.day || 1, dateInfo.hour || 0, dateInfo.minute || 0, dateInfo.second || 0, dateInfo.millisecond || 0);
    }
    return date;
}
function regexEscape(str) {
    return str.replace(/[|\\{()[^$+*?.-]/g, '\\$&');
}
function shorten(arr, sLen) {
    var newArr = [];
    for (var i = 0, len = arr.length; i < len; i++) {
        newArr.push(arr[i].substr(0, sLen));
    }
    return newArr;
}
function monthUpdate(arrName) {
    return function (d, v, i18n) {
        var index = i18n[arrName].indexOf(v.charAt(0).toUpperCase() + v.substr(1).toLowerCase());
        if (~index) {
            d.month = index;
        }
    };
}
function setMonth(d, v) {
    var m = parseInt(v, 10);
    d.month = m - 1;
}
function setDay(d, v) {
    d.day = parseInt(v, 10);
}
function setHour(d, v) {
    d.hour = parseInt(v, 10);
}
function setMinute(d, v) {
    d.minute = parseInt(v, 10);
}
function setSecond(d, v) {
    d.second = parseInt(v, 10);
}
function setPm(d, v, i18n) {
    var val = v.toLowerCase();
    if (val === i18n.amPm[0]) {
        d.isPm = false;
    }
    else if (val === i18n.amPm[1]) {
        d.isPm = true;
    }
}
function pad(val, len) {
    if (len === void 0) { len = 2; }
    val = String(val);
    while (val.length < len) {
        val = '0' + val;
    }
    return val;
}
