'use strict';

const React = require("react");
const createReactClass = require("create-react-class");
const classnames = require("classnames");
const filterValues = require("filter-values");

const renderIf = require("../../render-if");

const AstItemAttributeSeries = require("./attribute-series");
const AstItemAttribute = require("./sub-items/attribute");

function normalizeItemAttributes(attributes) {
	if (attributes == null) {
		return {};
	} else {
		return filterValues(attributes, (value) => {
			return (value != null);
		});
	}
}

module.exports = function ({dependencies}) {
	dependencies.set("AstItem", createReactClass({
		displayName: "AstItem",
		getInitialState: function () {
			return {
				collapsed: false
			};
		},
		toggleCollapsed: function () {
			this.setState({
				collapsed: !this.state.collapsed
			});
		},
		render: function () {
			let attributes = normalizeItemAttributes(this.props.attributes);
			let children = normalizeItemAttributes(this.props.children);
			let childSequences = normalizeItemAttributes(this.props.childSequences);
			let hasContents = (Object.keys(attributes).length > 0 || Object.keys(children).length > 0 || Object.keys(childSequences).length > 0);

			return (
				<div className={classnames("astItem", {hasFunctionScope: this.props.hasFunctionScope, hasBlockScope: this.props.hasBlockScope})}>
					{renderIf(hasContents, <span className="arrow" onClick={this.toggleCollapsed}>
						{this.state.collapsed ? "▶" : "▼"}
					</span>)}

					<span className="type" onDoubleClick={this.toggleCollapsed}>
						{renderIf(this.props.abbreviated === true, "✂ ")}
						{this.props.type}
						{renderIf(this.props.preview != null, <span className="preview">{this.props.preview}</span>)}
					</span>

					{renderIf(this.props.scopeId != null, <span className="scopeId">
						Scope ID: {this.props.scopeId} [type: {this.props.scopeType}]
					</span>)}

					{/*(simple: {String(this.props.data.isSimple())})*/}

					{renderIf(this.state.collapsed === false, <span>
						<AstItemAttributeSeries className="attributes" itemType={AstItemAttribute} items={attributes} />
						<AstItemAttributeSeries className="children" itemType={dependencies.get("AstItemChild")} items={children} />
						<AstItemAttributeSeries className="childSequences" itemType={dependencies.get("AstItemChildSequence")} items={childSequences} />
					</span>)}
				</div>
			);
		}
	}));
};
