import React, { useReducer, useEffect, useState, Fragment } from 'react'
import { RouteComponentProps } from 'react-router'
import { reducer, initialState, getLayersAction, updateLayerAction, saveLayersAction, Item } from './reducer'
import VectorShow from '../components/VectorShow'

type Attr = 'lineColor' | 'lineWidth' | 'fillColor'

function StyleEdit(props: RouteComponentProps) {
  let [state, dispatch] = useReducer(reducer, initialState)
  let layers = Object.keys(state)
  let [layer, setLayer] = useState('')
  let params = props.match.params as any
  let style = (layer && state[layer]) as Item

  useEffect(() => { getLayersAction(dispatch, params.id) }, [params.id])
  useEffect(() => { layer || setLayer(layers[0]) }, [layer, layers])

  const changeHandle = (attr: Attr) => (ev: React.ChangeEvent<HTMLInputElement>) => {
    updateLayerAction(dispatch, layer, { ...style, [attr]: ev.target.value })
  }
  const saveHandle = () => { saveLayersAction(style, params.id) }
  const verctorInfo = style && { ...style, url: style.getUrl }

  return (
    <div>
      <select value={layer} onChange={ev => setLayer(ev.target.value)}>
        {layers.map(layer => <option value={layer} key={layer}>{layer}</option>)}
      </select>
      {style && (
        <Fragment>
          <input type="color" value={style.fillColor} onChange={changeHandle('fillColor')} />
          <input type="color" value={style.lineColor} onChange={changeHandle('lineColor')} />
          <input type="number" value={style.lineWidth} onChange={changeHandle('lineWidth')} />
          <button onClick={saveHandle}>保存</button>
        </Fragment>
      )}
      {style && <VectorShow {...verctorInfo} height={2500} />}
    </div>
  )
}

export default StyleEdit