import React, { Component } from 'react';
import './css/App.css';
import IntentList from './components/IntentList';
import IntentDetails from './components/IntentDetails';
import {getAllIntents, deleteIntent, updateIntent} from './lib/api'
class App extends Component {
constructor(props){
super(props);
this.state={allIntents:[], selectedIntent: {questions:[''],answer:''}, selectedIndex:-1};
getAllIntents().then(l=> l.text()).then(result=>{
this.setState({allIntents: JSON.parse(result), selectedIntent: this.state.selectedIntent})
})
this.handleIntentClick = this.handleIntentClick.bind(this);
this.handleDeleteIntentClick = this.handleDeleteIntentClick.bind(this);
this.handleSaveIntentClick = this.handleSaveIntentClick.bind(this);
this.handleAddIntentClick = this.handleAddIntentClick.bind(this);
}
render() {
return (
);
}
handleIntentClick(selectedIntent, index){
this.setState({selectedIntent:selectedIntent, selectedIndex: index});
}
handleDeleteIntentClick(selectedIntent){
if (selectedIntent._id){
deleteIntent(selectedIntent._id).then(l=>l.text()).then(result=>{
if (JSON.parse(result).n===1){
let id = this.state.allIntents.indexOf(selectedIntent);
if (id!==-1){
this.state.allIntents.splice(id,1);
this.setState({allIntents: this.state.allIntents, selectedIntent: {questions:[''],answer:''}});
}else{
alert("Error");
}
}else{
alert("Error");
}
});
}
}
handleSaveIntentClick(selectedIntent){
updateIntent(selectedIntent._id, selectedIntent).then(l=>l.text()).then(result=>{
if (JSON.parse(result).nModified===1){
this.state.allIntents.map((intent,index)=>{
if (intent._id === selectedIntent._id){
let newAllIntents = this.state.allIntents;
newAllIntents[index] = selectedIntent;
this.setState({allIntents: newAllIntents, selectedIntent: selectedIntent});
return 1;
}
});
}else{
alert("error - update went wrong");
}
});
}
handleAddIntentClick(){
this.setState({allIntents: this.state.allIntents, selectedIntent: {questions:[''], answer:''}});
}
}
export default App;