import AttrListEdit from './components/AttrListEdit.jsx';
import JsonDisplay from './components/JsonDisplay.jsx';

function ExtendedAttributesEdit({attributes, setAttributes, ...props}) {
	console.log("rendering with attributes: ", attributes);

	if (!attributes) {
		return <section className="page-contents">Attributes is falsy!</section>;
	}

	function attributeListSetter(attributeName) {
		return (newValue) => setAttributes((a) => {
			if (a === null) return a;
			let newList = {...a}
			newList[attributeName] = newValue; 
			return newList;
		});
	}

	const newAttributes = {...attributes, 
		parent: undefined,
		location: undefined,
		contents: undefined,
		verbs: undefined,
		prepositions: undefined
	}

	let parentSnip;
	if (!attributes.hasOwnProperty("parent") || attributes.parent === null || attributes.parent === undefined) {
		parentSnip = <section className="page-contents">
			This object does not have a parent.
			<button
				onClick={() => setAttributes((a) => {return {...a, parent: ""}}) }
				>
				Set Parent
			</button>
		</section>;
	} else {
		parentSnip = <section className="page-contents">
			The parent of this object is #
			<input 
				type="text"
				value={`${attributes.parent}`}
				onChange={(e) => {
						const val = e.target.value;
						setAttributes((a) => {return {...a, parent: Number(val) };}); 
					}}
				/>.
			<button
				onClick={() =>setAttributes((a) => {return {...a, parent: undefined};})} >
				Clear Parent 
			</button>
		</section>;
	}

	let locationSnip;
	if (!attributes.hasOwnProperty("location") || attributes.location === null || attributes.location === undefined) {
		locationSnip = <section className="page-contents">
			This object does not have a location.
			<button
				onClick={() => setAttributes((a) => {return {...a, location: ""}}) }
				>
				Set Location
			</button>
		</section>;
	} else {
		locationSnip = <section className="page-contents">
			The location of this object is #
			<input 
				type="text"
				value={attributes.location}
				onChange={(e) => {
						const val = e.target.value;
						setAttributes((a) => {return {...a, location: Number(val) };}); 
					}}
				/>.
			<button
				onClick={() => setAttributes((a) => {return {...a, location: undefined};})} >
				Clear Location 
			</button>
		</section>;
	}

	return <>
		{parentSnip}

		{locationSnip}

		<AttrListEdit 
			title="Contents of this location:"
			list={attributes.contents}
			onChange={attributeListSetter('contents')} />

		<AttrListEdit
			title="Verbs defined on this object:"
			list={attributes.verbs} 
			onChange={attributeListSetter('verbs')} />

		<AttrListEdit
			title="Prepositions this verb expects:"
			list={attributes.prepositions} 
			onChange={attributeListSetter('prepositions')} />

		<JsonDisplay
			obj={newAttributes} />
	</>
}

export default ExtendedAttributesEdit;