import React, { Component } from 'react' import styled from 'styled-components' import { connect } from 'react-redux' import { Redirect, Link } from 'react-router-dom' import Input from './parts/Input' import Select from './parts/Select' import { updateRoute, createRoute, deleteRoute } from '../actions/route'; import store from '../store' const StyledRouteForm = styled.div` padding: 1rem; background: #fafafa; ` // TODO: need to deal with shapes class RouteForm extends Component { state = { id: null, agency: null, route_id: "", short_name: "", long_name: "", desc: "", route_type: "3", route_url: "", route_color: "", route_text_color: "", route_sort_order: "0", } constructor() { super() this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) this.handleDelete = this.handleDelete.bind(this) this.renderForm = this.renderForm.bind(this) } handleChange(evt) { let updated = {} updated[evt.target.name] = evt.target.value this.setState(updated) } handleSubmit() { const { id } = this.state let body = { ...this.state } delete body.id delete body.farerule_set delete body.trip_set delete body.geojson if (id !== null) { store.dispatch(updateRoute(id, body)) } else { store.dispatch(createRoute(body)) } this.setState({justSubmit: true}) } handleDelete() { const { id } = this.state store.dispatch(deleteRoute(id)) this.setState({justSubmit: true}) } static getDerivedStateFromProps(props, state) { // if form is ready, then nothing else to do if (state.agency !== null || state.id !== null) return null const { agencyId, routeId } = props.match.params if (routeId === undefined && state.agency === null && props.agency.count > 0) { // this is for new route const { results } = props.agency const agencies = results.filter(ele => ele.agency_id === agencyId) if (agencies.length > 0) { props.updateBreadcrumb({ agencyId, routeId: 'new' }) return { agency: agencies[0].id } } } else if (routeId !== undefined && state.id === null) { // this is for editing route const ones = props.route.results.filter(ele => ele.route_id === routeId) props.updateBreadcrumb({ agencyId, routeId }) return ones[0] } return null } renderForm() { const one = this.state const { agencyId, routeId } = this.props.match.params const { agency } = this.props const agencies = agency.results.filter(ele => ele.agency_id === agencyId) const { fetching } = this.props.route return (

{one.route_id || 'New Route'}  

{one.id !== null &&
}
{agencies[0] && Cancel}
) } render () { const one = this.state const { fetching } = this.props.agency // redirect to view page if no data const { agencyId } = this.props.match.params // redirect to agency list if submitted if (one.justSubmit === true && !fetching) { return } return this.renderForm() } } const mapStateToProps = state => ({ agency: state.agency, route: state.route, }) const connectRouteForm = connect( mapStateToProps, )(RouteForm) export default connectRouteForm