import { getLayerById } from '../Map/Utils';

import MapContext from '../Map/MapContext';

import './LayerTree.css';
import LayerActionDownload from './actions/LayerActionDownload';
import LayerActionZoomToLayer from './actions/LayerActionZoomToLayer';
import LayerActionOpacity from './actions/LayerActionOpacity';
import LayerActionSwipe from './actions/LayerActionSwipe';

import React, { useState, useContext, useEffect } from 'react';
import { Tree, Space, Typography } from 'antd';
const { DirectoryTree } = Tree;

const { Text } = Typography;


/**
 * @component
 * @category LayerSwitcher
 */
function LayerTree (props){

    const { t, model } = props;

	const [checkedKeys, setCheckedKeys] = useState([]);
    const { map } = useContext(MapContext);
	
	const onCheck = (checkedKeys, info) => {
		setCheckedKeys(checkedKeys);
		map.getLayers().forEach(function (layer, i) {
            if (!layer.baselayer) {
				let visible = false;
                for (let i=0; i<checkedKeys.checked.length; i++) {
					if (layer.id == checkedKeys.checked[i]) {
						visible = true;
					}
				 }
				 if (layer.allwaysVisible) {
					 visible = true;
				 }
				 layer.setVisible(visible);
            }
        });
		
	};

	const initTree = (tree, checked) => {
		
		for (let i in tree) {
			if (!tree[i].isLayer) {
				initTree(tree[i].children, checked);
	
			} else {
				if (tree[i].visible) {
					checked.push(tree[i].key);
				}
			}
		}
		setCheckedKeys(checked);
		
	};

	useEffect(() => {
		let checked = [];
		initTree(model, checked);
    }, []);

    return (
		<DirectoryTree
      		checkable
			checkStrictly={true}
			defaultExpandedKeys={['0']}
			checkedKeys={checkedKeys}
      		treeData={model}
			onCheck={onCheck}
			titleRender={(treeNode) => {
				if (treeNode.isLeaf) {
					let layerId = treeNode.parent;
					let layer = getLayerById(map, layerId);
					return (
						<Space style={{width: '300px'}} direction="vertical">
							{ treeNode.showLayerActions ? <Space>
								<LayerActionDownload t={t} olLayer={layer}/>
								<LayerActionZoomToLayer t={t} olLayer={layer}/>
							</Space> : null }
							<LayerActionOpacity t={t} olLayer={layer}/>
							<LayerActionSwipe t={t} olLayer={layer}/>
						</Space>
				  	);
				}
				if (treeNode.isGroup) {
					return <Text strong>{treeNode.title}</Text>;
				}
				return 	<>
							{/*<BorderOutlined style={{color: treeNode.symbol_stroke, backgroundColor: treeNode.symbol_fill, marginRight: '5px'}}/>*/}
							<Text type="secondary">{treeNode.title}</Text>
						</>;
			  }}
			/>
	);
}

export default LayerTree;