import http from '../../http'
import { LayerStyle } from '../components/VectorShow'

export const ADDLAYER = Symbol('add_layer')
export const UPDATELAYER = Symbol('update_layer')
export const DELLAYER = Symbol('del_layer')
export const LOADLAYERS = Symbol('load_layers')

export interface Item extends LayerStyle {
  show: boolean,
  url: string,
  checked: boolean,
  lat: number,
  lng: number
}

export interface State {
  [key: string]: Item
}

export interface Action {
  type: any,
  plyload: any | {
    layer: string,
    value?: any
  }
}

export interface Dispatch {
  (args: Action): void
}

export const defaultLayerStyle = (): Item => ({
  lineColor: '#000000',
  lineWidth: 2,
  fillColor: '#000000',
  show: false,
  checked: false,
  url: '',
  lat: 0,
  lng: 0
})

export const initialState : State = { }

export function reducer(state: State, action: Action) : State {
  let cstate = state
  let key = action.plyload.layer

  switch (action.type) {
    case LOADLAYERS: 
      cstate = { ...action.plyload }
      break;
    case ADDLAYER: 
      if (!state[key]) {
        cstate = {
          ...state, 
          [key]: action.plyload.value || defaultLayerStyle()
        }
      }
      break;
    case UPDATELAYER:
      if (state[key]) {
        cstate = {
          ...state,
          [key]: action.plyload.value as Item
        }
      }      
      break;
    case DELLAYER: 
      if (state[key]) {
        cstate = { ...state }
        delete cstate[key]
      }
      break;
  }

  return cstate
}

interface ActionFun {
  (dispatch: Dispatch, layer: string, value: Item): void
}

export const addLayerAction: ActionFun = (dispatch, layer, value = defaultLayerStyle()) => dispatch({ type: ADDLAYER, plyload: { layer, value } })
export const updateLayerAction: ActionFun = (dispatch, layer, value) => dispatch({ type: UPDATELAYER, plyload: { layer, value } })
export const delLayerAction: ActionFun = (dispatch, layer) => dispatch({ type: DELLAYER, plyload: { layer } })

export const getLayersAction = async (dispatch: Dispatch, id: number) => {
  let res = await http.get('/vector/style/get/' + id + '/')
  if (!res.data.data) return;
  let layer = JSON.parse(res.data.data.layer)
  let style = {
    ...defaultLayerStyle(),
    ...layer
  }
  addLayerAction(dispatch, layer.id, style)
  console.log(style)
}