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

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

const PREV = process.env.NODE_ENV === 'development' ? '/test/data' : '/data'

export interface Item extends LayerStyle {
  show: boolean,
  url: string,
  getUrl: 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: '',
  getUrl: '',
  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 + '/')
  let data = res.data.data
  if (!data) return;

  let layer = data.content ? JSON.parse(data.content) : JSON.parse(data.layer)
  let style = {
    ...defaultLayerStyle(),
    ...layer,
    lat: Number(data.latitude),
    lng: Number(data.longitude),
    url: layer.url,
    getUrl: path.join(PREV, layer.url, '/{z}/{x}/{y}.pbf')
  }

  addLayerAction(dispatch, layer.name, style)
}

export const saveLayersAction = async (style: Item, id: number) => {
  try {
    let res = await http.post('/vector/style/save/', {
      outputFileId: id,
      content: JSON.stringify(style)
    })
    return res.data.status === 200
  } catch {
    return false
  }
}