const expandAll = () => {
	const details = document.querySelectorAll("details");
	details.forEach((detail) => {detail.setAttribute("open", "true")})
}

const collapseAll = () => {
	const details = document.querySelectorAll("details");
	details.forEach((detail) => {detail.removeAttribute("open")})
}

class ExpandAllButton extends React.Component {
	render() {
		return (<button onClick={e => expandAll()}>expand all</button>);
	}
};

class CollapseAllButton extends React.Component {
	render() {
		return (<button onClick={e => collapseAll()}>collapse all</button>);
	}
};


/*
var common_componentDidMount = function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState(data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
}
*/
var Main = React.createClass({
	//getInitialState: function() { return {'nodes': {}}; },
/*	componentDidMount: function() {
		$.ajax({
			url: '/longpoll',
			dataType: 'json',
			cache: false,
			success: function(data) {
				this.setState({'nodes': data});
			}.bind(this),
			error: function(xhr, status, err) {
				console.error(this.props.url, status, err.toString());
			}.bind(this),
		});
	},*/
	render: function() {
		var keys = Object.keys(this.props.nodes).sort();
		var nodes = [];
		for (var k of keys) {
			var v = this.props.nodes[k];
			nodes.push(React.createElement(Node, {url: '/' + k, key: k, data: v}));
		}

		return (
			<div>
				<h1>simulator</h1>
				<ExpandAllButton></ExpandAllButton>
				<CollapseAllButton></CollapseAllButton>
				<div className="main">{nodes}</div>
			</div>
		);
	}
});


var Node = React.createClass({
	//getInitialState: function() { return {}; },
	//componentDidMount: common_componentDidMount,

	on_key_down: function(e) {
		if (e.which != 13) return;
		console.log('on_key_down', this.props.url);
		var name = e.target.getAttribute('data-override-name');
		var val = e.target.value;
		$.ajax({
			url: this.props.url + '/override/' + name + '/' + val,
			//dataType: 'json',
			//cache: false,
			success: function(data) {
				console.log(this.props.url, 'ok');
			}.bind(this),
			error: function(xhr, status, err) {
				console.error(this.props.url, status, err.toString());
			}.bind(this),
			timeout: 5000,
		});
	},

	on_click: function(e) {
		console.log('on_click', this.props.url);
		var name = e.target.getAttribute('data-override-name');
		$.ajax({
			url: this.props.url + '/action/' + name,
			//dataType: 'json',
			//cache: false,
			success: function(data) {
				console.log(this.props.url, 'ok');
			}.bind(this),
			error: function(xhr, status, err) {
				console.error(this.props.url, status, err.toString());
			}.bind(this),
			timeout: 5000,
		});
	},

	render: function() {
		var info_str = JSON.stringify(this.props.data['info'], null, 2);
		var overrides = [];
		for (var k in this.props.data['overrides']) {
			var v = this.props.data['overrides'][k];
			overrides.push(<div>{k}: {JSON.stringify(v, null, 2)} <input key={this.props.url + '/override/' + k} data-override-name={k} onKeyDown={this.on_key_down} size="1" /></div>);
		}
		var actions = [];
		for (var k in this.props.data['actions']) {
			var v = this.props.data['actions'][k];
			actions.push(<button key={this.props.url + '/action/' + v} data-override-name={v} onClick={this.on_click}>{v}</button>);
		}
		return (
			<div className="node">
				{this.props.url}:
				<details>
					<summary>...</summary>
					<pre>{info_str}</pre>
					<div className='overrides'>{overrides}</div>
					<div className='actions'>{actions}</div>
				</details>
			</div>
		)
	},
});

//ReactDOM.render(<Main />, document.getElementById('content'));

var source = new EventSource('/stream');
source.addEventListener('message', function(e) {
	//console.log('Received a message:', e.data);

	var data = JSON.parse(e.data);
	for (var key in data) {
		var val = data[key];
		//console.log(key, val);

		//var el = document.getElementById(key);
		//if (!el) continue;

		//ReactDOM.findDOMNode(key).setState(val["info"]);
	}

	ReactDOM.render(<Main nodes={data}/>, document.getElementById('content'));
});
