import React from 'react'
import cloneDeep from 'lodash.clonedeep'
import Button from '../Button'
import LayerListGroup from './LayerListGroup'
import LayerListItem from './LayerListItem'
import AddIcon from 'react-icons/lib/md/add-circle-outline'
import AddModal from '../modals/AddModal'
import style from '../../libs/style.js'
import {SortableContainer, SortableHandle, arrayMove} from 'react-sortable-hoc';
const layerPrefix = name => name.replace(' ', '-').replace('_', '-').split('-')[0]
const layerListPropTypes = {
layers: React.PropTypes.array.isRequired,
selectedLayerIndex: React.PropTypes.number.isRequired,
onLayersChange: React.PropTypes.func.isRequired,
onLayerSelect: React.PropTypes.func,
sources: React.PropTypes.object.isRequired,
}
// List of collapsible layer editors
@SortableContainer
class LayerListContainer extends React.Component {
static propTypes = {...layerListPropTypes}
static defaultProps = {
onLayerSelect: () => {},
}
constructor(props) {
super(props)
this.state = {
isOpen: {
add: false,
}
}
}
onLayerDestroy(layerId) {
const remainingLayers = this.props.layers.slice(0)
const idx = style.indexOfLayer(remainingLayers, layerId)
remainingLayers.splice(idx, 1);
this.props.onLayersChange(remainingLayers)
}
onLayerCopy(layerId) {
const changedLayers = this.props.layers.slice(0)
const idx = style.indexOfLayer(changedLayers, layerId)
const clonedLayer = cloneDeep(changedLayers[idx])
clonedLayer.id = clonedLayer.id + "-copy"
changedLayers.splice(idx, 0, clonedLayer)
this.props.onLayersChange(changedLayers)
}
onLayerVisibilityToggle(layerId) {
const changedLayers = this.props.layers.slice(0)
const idx = style.indexOfLayer(changedLayers, layerId)
const layer = { ...changedLayers[idx] }
const changedLayout = 'layout' in layer ? {...layer.layout} : {}
changedLayout.visibility = changedLayout.visibility === 'none' ? 'visible' : 'none'
layer.layout = changedLayout
changedLayers[idx] = layer
this.props.onLayersChange(changedLayers)
}
toggleModal(modalName) {
this.setState({
isOpen: {
...this.state.isOpen,
[modalName]: !this.state.isOpen[modalName]
}
})
}
groupedLayers() {
const groups = []
for (let i = 0; i < this.props.layers.length; i++) {
const previousLayer = this.props.layers[i-1]
const layer = this.props.layers[i]
if(previousLayer && layerPrefix(previousLayer.id) == layerPrefix(layer.id)) {
const lastGroup = groups[groups.length - 1]
lastGroup.push(layer)
} else {
groups.push([layer])
}
}
return groups
}
toggleLayerGroup(groupPrefix) {
groupedLayers().forEach(layers => {
if(groupPrefix === layerPrefix(layers[0].id)) {
layers.forEach(layer => {
//HACK
//In this case it is ok to modify the metadata
//because no one else depends on it
layer.metadata = {
...layer.metadata,
'maputnik:visible': false
}
})
}
})
}
render() {
const listItems = []
let idx = 0
this.groupedLayers().forEach(layers => {
if(layers.length > 1) {
const groupPrefix = layerPrefix(layers[0].id)
const grp =