import React from "react"; //eslint-disable-line
import PropTypes from "prop-types";

import ObjectValue from "../object/ObjectValue"; //eslint-disable-line
import ObjectName from "../object/ObjectName"; //eslint-disable-line

/* NOTE: Chrome console.log is italic */
const styles = {
	preview: {
		fontStyle: "italic",
	},
};

/* intersperse arr with separator */
function intersperse(arr, sep) {
	if (arr.length === 0) {
		return [];
	}

	return arr.slice(1).reduce((xs, x) => xs.concat([sep, x]), [arr[0]]);
}

/**
 * A preview of the object
 */
const ObjectPreview = ({ onMatchFound, filterStrings, searchBoxText, data, maxProperties }) => {
	const object = data;

	const objectValueDefaults = {
		onMatchFound: () => {},
		searchBoxText: "",
		filterStrings: [],
	};

	if (typeof object !== "object" || object === null || object instanceof Date || object instanceof RegExp) {
		return <ObjectValue object={object} {...objectValueDefaults} />;
	}

	if (Array.isArray(object)) {
		return (
			<span style={styles.preview}>
				[
				{intersperse(
					object.map((element, index) => <ObjectValue key={index} object={element} {...objectValueDefaults} />),
					", "
				)}
				]
			</span>
		);
	}
	const propertyNodes: any[] = [];
	for (const propertyName in object) {
		const propertyValue = object[propertyName];
		if (object.hasOwnProperty(propertyName)) {
			let ellipsis;
			if (propertyNodes.length === maxProperties - 1 && Object.keys(object).length > maxProperties) {
				ellipsis = <span key="ellipsis">…</span>;
			}
			propertyNodes.push(
				<span key={propertyName}>
					<ObjectName
						onMatchFound={onMatchFound}
						searchBoxText={searchBoxText}
						filterStrings={filterStrings}
						name={propertyName || '""'}
					/>
					:&nbsp;
					<ObjectValue
						searchBoxText={searchBoxText}
						filterStrings={filterStrings}
						onMatchFound={onMatchFound}
						object={propertyValue}
					/>
					{ellipsis}
				</span>
			);
			if (ellipsis) break;
		}
	}

	return (
		<span style={styles.preview}>
			{`${object.constructor.name} {`}
			{intersperse(propertyNodes, ", ")}
			{"}"}
		</span>
	);
};

ObjectPreview.propTypes = {
	/**
	 * max number of properties shown in the property view
	 */
	maxProperties: PropTypes.number,
};
ObjectPreview.defaultProps = {
	maxProperties: 5,
};

export default ObjectPreview;
