frontend/smart-hut/src/views/Dashboard.js
2020-03-19 11:52:13 +01:00

148 lines
3.5 KiB
JavaScript

import React, {Component} from 'react';
import DevicePanel from "../components/dashboard/DevicePanel";
import Navbar from './Navbar'
import MyHeader from '../components/HeaderController'
import { call } from '../client_server';
import { Grid } from 'semantic-ui-react'
/*
rooms -> actual rooms
activeItem -> the current room in view
devices -> current device in current room view
id of Home is -1
*/
export default class Dashboard extends Component{
constructor(props) {
super(props);
this.state = {
rooms: [],
activeItem: -1,
devices: [],
tkn: this.props.tkn,
};
this.addRoom = this.addRoom.bind(this);
this.deleteRoom = this.deleteRoom.bind(this);
this.addDevice = this.addDevice.bind(this);
this.handleItemClick = this.handleItemClick.bind(this);
}
componentDidMount() {
call.getAllRooms(this.props.tkn)
.then(res => {
if (res.status === 200){
this.setState({
rooms: res.data
});
}
}).catch(err => {
console.log(err);
});
call.getAllDevices(this.props.tkn)
.then(res => {
if (res.status === 200) {
this.setState({
devices: res.data
});
}
}).catch(err => {
console.log(err);
});
}
addRoom(data) {
call.createRoom(data)
.then(res => {
if (res.status === 200 && res.data) {
this.setState(state => ({
rooms: state.rooms.concat([res.data])
}));
}
}).catch(err => {
console.log(err);
});
};
deleteRoom() {
let data = {
id : this.state.activeItem
}
call.deleteRoom(data)
.then(res => {
//remove room in state.rooms
}).catch(err => {
console.log(err);
});
}
handleItemClick(id) {
// el -> obj of name and id
//da fare richiesta get della room e settare activeItem
this.setState({
activeItem: id
});
if ( id === -1) {
call.getAllDevices(this.props.tkn)
.then(res => {
if ( res.status === 200) {
this.setState({
devices: res.data
});
}
}).catch(err => {
console.log(err);
});
} else {
call.getAllDevicesByRoom(id, this.props.tkn)
.then(res => {
if (res.status === 200) {
this.setState({
devices: res.data
});
}
}).catch(err => {
console.log(err);
});
}
}
addDevice(data) {
data.params["roomId"] = this.state.activeItem;
call.devicePost(data, this.props.tkn)
.then(res => {
this.setState(state => ({
devices: state.devices.concat([res.data])
}));
}).catch(err => {
});
return this.state.devices;
}
render () {
return(
<div style={{height : "110vh", background: '#1b1c1d'}}>
<Grid >
<Grid.Row color='black'>
<Grid.Column>
<MyHeader logout={this.props.logout} />
</Grid.Column>
</Grid.Row>
<Grid.Row color='black'>
<Grid.Column width={3}>
<Navbar addRoom={this.addRoom} deleteRoom={this.deleteRoom} rooms={this.state.rooms} handleItemClick={this.handleItemClick}/>
</Grid.Column>
<Grid.Column width={13}>
<DevicePanel addDevice={this.addDevice} devices={this.state.devices} />
</Grid.Column>
</Grid.Row>
</Grid>
</div>
)
}
}