/*
 * Utils functions
 *
 */

/**
 * Break string str each maxLen symbols
 * @param str
 * @param maxLen
 * @returns {string}
 */
module.exports.linebrk = function (str, maxLen) {
    var res = '';
    var i = 0;
    while (i + maxLen < str.length) {
        res += str.substring(i, i + maxLen) + "\n";
        i += maxLen;
    }
    return res + str.substring(i, str.length);
};

/**
 * Trying get a 32-bit unsigned integer from the partial buffer
 * @param buffer
 * @param offset
 * @returns {Number}
 */
module.exports.get32IntFromBuffer = function (buffer, offset) {
    offset = offset || 0;
    var size = 0;
    if ((size = buffer.length - offset) > 0) {
        if (size >= 4) {
            return buffer.readUInt32BE(offset);
        } else {
            var res = 0;
            for (var i = offset + size, d = 0; i > offset; i--, d += 2) {
                res += buffer[i - 1] * Math.pow(16, d);
            }
            return res;
        }
    } else {
        return NaN;
    }
};

module.exports._ = {
    isObject: function (value) {
        var type = typeof value;
        return !!value && (type == 'object' || type == 'function');
    },

    isString: function (value) {
        return typeof value == 'string' || value instanceof String;
    },

    isNumber: function (value) {
        return typeof value == 'number' || !isNaN(parseFloat(value)) && isFinite(value);
    },

    /**
     * Returns copy of `obj` without `removeProp` field.
     * @param obj
     * @param removeProp
     * @returns Object
     */
    omit: function (obj, removeProp) {
        var newObj = {};
        for (var prop in obj) {
            if (!obj.hasOwnProperty(prop) || prop === removeProp) {
                continue;
            }
            newObj[prop] = obj[prop];
        }

        return newObj;
    }
};

/**
 * Strips everything around the opening and closing lines, including the lines
 * themselves.
 */
module.exports.trimSurroundingText = function (data, opening, closing) {
    var trimStartIndex = 0;
    var trimEndIndex = data.length;

    var openingBoundaryIndex = data.indexOf(opening);
    if (openingBoundaryIndex >= 0) {
        trimStartIndex = openingBoundaryIndex + opening.length;
    }

    var closingBoundaryIndex = data.indexOf(closing, openingBoundaryIndex);
    if (closingBoundaryIndex >= 0) {
        trimEndIndex = closingBoundaryIndex;
    }

    return data.substring(trimStartIndex, trimEndIndex);
}
