frontend/smart-hut/src/components/dashboard/devices/Curtain.js

102 lines
2.7 KiB
JavaScript
Raw Normal View History

2020-04-23 14:02:02 +00:00
import React, {Component} from "react";
import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
import {Slider} from "@material-ui/core";
class Curtain extends Component {
constructor (props){
super(props);
this.state = { intensity: this.props.device.intensity, timeout: null };
this.setIntensity = this.setIntensity.bind(this);
}
//getters
get turnedOn() {
return this.props.device.on;
}
get intensity() {
return this.props.device.intensity || 0;
}
onClickDevice = () => {
const on = !this.turnedOn;
this.props
.saveDevice({ ...this.props.device, on })
.catch((err) => console.error("curtains update error", err));
};
setIntensity(intensity) {
intensity *= 100;
if (this.state.timeout) {
clearTimeout(this.state.timeout);
}
this.setState({
intensity,
timeout: setTimeout(() => {
this.saveIntensity();
this.setState({
intensity: this.state.intensity,
timeout: null,
});
}, 100),
});
}
saveIntensity = () => {
const intensity = Math.round(this.state.intensity);
this.props
.saveDevice({ ...this.props.device, intensity })
.catch((err) => console.error("curtains update error", err));
};
helper=()=>{
if(this.props.device.intensity>=90){
this.setIntensity(1);
this.saveIntensity();
}else {
this.setIntensity(this.props.device.intensity / 100 + 0.10);
this.saveIntensity();
}
};
helper2=()=>{
if(this.props.device.intensity<=10){
this.setIntensity(0);
this.saveIntensity();
}else {
this.setIntensity(this.props.device.intensity / 100 - 0.10);
this.saveIntensity();
}
};
helper3=(a)=>{
//console.log(a);
this.setIntensity(a/100);
this.saveIntensity();
};
///*this took me way too much more time than it should have*/
render(){
return <div><p>{this.props.device.intensity}</p>
<Slider
min={0} value={this.props.device.intensity} max={100} onChange={ (e, val) => {this.helper3(val)}}
/>
<input type="submit" value="increase" onClick={this.helper}/>
<input type="submit" value="decrease" onClick={this.helper2}/>
</div>;
}
}
const mapStateToProps = (state, ownProps) => ({
device: state.devices[ownProps.id],
});
const CurtainContainer = connect(mapStateToProps, RemoteService)(Curtain);
export default CurtainContainer;