'use strict';
var isObj = require('is-obj');

module.exports.get = function (obj, path) {
	if (!isObj(obj) || typeof path !== 'string') {
		return obj;
	}

	var pathArr = getPathSegments(path);

	for (var i = 0; i < pathArr.length; i++) {
		var descriptor = Object.getOwnPropertyDescriptor(obj, pathArr[i]) || Object.getOwnPropertyDescriptor(Object.prototype, pathArr[i]);
		if (descriptor && !descriptor.enumerable) {
			return;
		}

		obj = obj[pathArr[i]];

		if (obj === undefined || obj === null) {
			// `obj` is either `undefined` or `null` so we want to stop the loop, and
			// if this is not the last bit of the path, and
			// if it did't return `undefined`
			// it would return `null` if `obj` is `null`
			// but we want `get({foo: null}, 'foo.bar')` to equal `undefined` not `null`
			if (i !== pathArr.length - 1) {
				return undefined;
			}

			break;
		}
	}

	return obj;
};

module.exports.set = function (obj, path, value) {
	if (!isObj(obj) || typeof path !== 'string') {
		return;
	}

	var pathArr = getPathSegments(path);

	for (var i = 0; i < pathArr.length; i++) {
		var p = pathArr[i];

		if (!isObj(obj[p])) {
			obj[p] = {};
		}

		if (i === pathArr.length - 1) {
			obj[p] = value;
		}

		obj = obj[p];
	}
};

module.exports.delete = function (obj, path) {
	if (!isObj(obj) || typeof path !== 'string') {
		return;
	}

	var pathArr = getPathSegments(path);

	for (var i = 0; i < pathArr.length; i++) {
		var p = pathArr[i];

		if (i === pathArr.length - 1) {
			delete obj[p];
			return;
		}

		obj = obj[p];
	}
};

module.exports.has = function (obj, path) {
	if (!isObj(obj) || typeof path !== 'string') {
		return false;
	}

	var pathArr = getPathSegments(path);

	for (var i = 0; i < pathArr.length; i++) {
		obj = obj[pathArr[i]];

		if (obj === undefined) {
			return false;
		}
	}

	return true;
};

function getPathSegments(path) {
	var pathArr = path.split('.');
	var parts = [];

	for (var i = 0; i < pathArr.length; i++) {
		var p = pathArr[i];

		while (p[p.length - 1] === '\\' && pathArr[i + 1] !== undefined) {
			p = p.slice(0, -1) + '.';
			p += pathArr[++i];
		}

		parts.push(p);
	}

	return parts;
}
