'use strict';

const moment = require('moment');

var isDate = function (dateObject) {
    if (Object.prototype.toString.call(dateObject) === "[object Date]") {
        if (isNaN(dateObject.getTime()) === false) {
            return true;
        }
    }
    return false;
};

module.exports = {
    //UTCTime must be formatted at ISOString i.e 2015-04-08T12:12:12.000Z
    getLocalFromUTCString : function(UTCTime){
        var localTime = new Date(UTCTime); //It'll convert the utc -> localtime
        return localTime;
    },
    //LocalTime must be formatted at ISOString i.e 2015-04-08T12:12:12.000Z
    getUTCFromLocalString : function(localTime){
        var dateTime = localTime.replace('T', ' ').replace('Z','');
        dateTime = new Date(dateTime); //create date object
        return dateTime.toISOString();
    },
    parseDate : function(date, format){
        var result = moment(date).format(format);
        return result;
    },
    isDate: isDate,
    convertToDate: function(date) {
        if(isDate(date)) {
           return date;
        } else if (!isNaN(date)) {
           return new Date(date);
        } else {
            // turning on strict parsing with the true at the end of the moment() call
            date = moment(date, ["DD/MM/YYYY hh:mm a", "DD/MM/YYYY", "hh:mm a", moment.ISO_8601], true);
            if (date.isValid()) {
                return date.toDate();
            } else {
                return null;
            }
        }
    },
    compare: function(date1, date2) {
        var time1 = new Date(date1).getTime();
        var time2 = new Date(date2).getTime();
        return (time1 - time2);
    },
    convertDateStringsToDates: function(input) {
        // Ignore things that aren't objects.
        if (typeof input !== "object") return input;

        var regexIso8601 =
            /^(\d{4}|\+\d{6})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})\.(\d{1,})(Z|([\-+])(\d{2}):(\d{2}))?)?)?)?$/;

        for (var key in input) {
            if (!input.hasOwnProperty(key)) continue;

            var value = input[key];
            var match;
            // Check for string properties which look like dates.
            // TODO: Improve this regex to better match ISO 8601 date strings.
            if (typeof value === "string" && (match = value.match(regexIso8601))) {
                // Assume that Date.parse can parse ISO 8601 strings, or has been shimmed in older browsers to do so.
                var milliseconds = Date.parse(match[0]);
                if (!isNaN(milliseconds)) {
                    input[key] = new Date(milliseconds);
                }
            } else if (typeof value === "object") {
                // Recurse into object
                this.convertDateStringsToDates(value);
            }
        }
    }
};
