frontend/smart-hut/src/components/dashboard/DevicePanel.js
2020-04-09 17:24:30 +02:00

122 lines
3.3 KiB
JavaScript

// vim: set ts=2 sw=2 et tw=80:
import React, { Component } from "react";
import { Grid } from "semantic-ui-react";
import { editButtonStyle, panelStyle } from "./devices/styleComponents";
import { checkMaxLength, DEVICE_NAME_MAX_LENGTH } from "./devices/constants";
import DeviceType from "./devices/DeviceTypeController";
import NewDevice from "./devices/NewDevice";
import SettingsModal from "./devices/SettingsModal";
import { connect } from "react-redux";
import { RemoteService } from "../../remote";
class DevicePanel extends Component {
constructor(props) {
super(props);
this.state = {
editMode: false,
};
this.addDevice = this.addDevice.bind(this);
this.toggleEditMode = this.toggleEditMode.bind(this);
this.getDevices();
}
toggleEditMode(e) {
this.setState((prevState) => ({ editMode: !prevState.editMode }));
}
openModal = (settingsDeviceId) => {
this.setState((prevState) => ({
openSettingsModal: !prevState.openSettingsModal,
settingsDeviceId: settingsDeviceId,
}));
};
/*changeDeviceData = (deviceId, newSettings) => {
console.log(newSettings.name, " <-- new name --> ", deviceId);
for (let prop in this.props.devices[deviceId]) {
if (prop === "name") {
if (checkMaxLength(newSettings[prop])) {
device[prop] = newSettings[prop];
} else {
alert(
"Name must be less than " +
DEVICE_NAME_MAX_LENGTH +
" characters."
);
}
} else {
device[prop] = newSettings[prop];
}
}
};*/
getDevices() {
this.props.fetchDevices().then();
}
render() {
const edit = {
mode: this.state.editMode,
openModal: this.openModal,
};
/*var backGroundImg =
this.props.activeItem === -1 ? "" : this.props.room.image;*/
const ds = this.state.devices ? this.state.devices : this.props.devices;
return (
<div style={panelStyle}>
<button style={editButtonStyle} onClick={this.editModeController}>
Edit
</button>
<Grid doubling columns={4} divided="vertically">
{this.state.openSettingsModal ? (
<SettingsModal
openModal={this.openModal}
device={ds.filter((d) => d.id === this.state.settingsDeviceId)[0]}
/>
) : (
""
)}
{this.props.devices.map((e, i) => {
return (
<Grid.Column key={i}>
<DeviceType type={e.kind} device={e} edit={edit} />
</Grid.Column>
);
})}
{!this.props.isActiveRoomHome ? (
<Grid.Column>
<NewDevice />
</Grid.Column>
) : null}
</Grid>
</div>
);
}
}
const mapStateToProps = (state, _) => ({
get devices() {
if (state.active.activeRoom === -1) {
return Object.values(state.devices);
} else {
return state.rooms[state.active.activeRoom].devices.map(
(id) => state.devices[id]
);
}
},
get isActiveRoomHome() {
return this.props.activeRoom === -1;
},
activeRoom: state.active.activeRoom,
});
const DevicePanelContainer = connect(
mapStateToProps,
RemoteService
)(DevicePanel);
export default DevicePanelContainer;