import React, { Component } from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import _ from "lodash";

import { writeTag } from "../actions/actions_tags";



export class TagsIndex extends Component {

	constructor(props){
		super(props);
		this.state = {writes: {}};
	}

	renderTagsList(){
		return _.map(this.props.tags, (t) => {
			return (<tr key={t.tagName}>
				<td>{t.tagName}</td>
				<td>{Math.round(t.value * 100) / 100}</td>
				<td><input 
					onChange={(e) => this.onTagWriteFieldChanged(e, t.tagName)}
					className="tag-write-input"
				/></td>
				<td><button 
					className="waves-effect waves-light btn tag-write-button"
					onClick={() => this.onWriteButtonClick(t.tagName)}
				>Write</button></td>
			</tr>);
		});
	}

	onWriteButtonClick = (tagName) => {
		this.props.writeTag(tagName, this.state.writes[tagName]);
	}

	onTagWriteFieldChanged = (e, tagName) => {
		this.setState({writes: {...this.state.writes, [tagName]: e.target.value}});
	}

	render() {
		let PLC = "PLC";
		if (this.props.plc.details){
			PLC = this.props.plc.details.name;
		}

		if (!this.props.tags || _.map(this.props.tags, (t)=> t ).length === 0) {
			return (
				<div style={styles.container}
					className="tags-index-notags"
				>
					<h3>
            No Tags.
					</h3>
					<h4>Add some in <Link to="/settings">Settings</Link>.</h4>
				</div>
			);
		}

		return (
			<div style={styles.container} className="tags-index-withtags">
				<h2>Tags for {this.props.plc.ipAddress}</h2>
				<h3>{PLC}</h3>
				<table className="table">
					<thead>
						<tr>
							<th>Tag Name</th>
							<th>Value</th>
							<th></th>
							<th></th>
						</tr>
					</thead>
					<tbody>
						{ this.renderTagsList()}
					</tbody>
				</table>
			</div>
		);
	}
}

const styles = {
	container: {
		height: "100%",
		display: "flex",
		flexDirection: "column",
		justifyContent: "space-around",
		textAlign: "center"
	},
	buttonContainer: {
		display: "flex",
		flexDirection: "column"
	},
	button: {
		marginBottom: "15px"
	},
	valueLabel: {
		fontSize: "1.5em"
	},
	topLabel: {
		fontSize: "1.35em"
	},
	minMaxLabel: {
		fontSize: "0.85em"
	}
};

/**
 * Map Redux state to React props
 * 
 * @param  {Object} state
 * 
 * @returns {Object} mapped state
 */
export function mapStateToProps(state){
	return {
		tags: state.tags,
		plc: state.plc
	};
}

export default connect(mapStateToProps, { writeTag })(TagsIndex);
