﻿import React from 'react';
import SortableTree, { toggleExpandedForAll } from 'react-sortable-tree-patch-react-17';
import FormBotones from '../botonera/formBotones.jsx';
import CajaTexto from '../cajaTexto/cajaTexto.jsx';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faMinus, faPlus, faBackward, faForward } from '@fortawesome/free-solid-svg-icons';
const maxDepth = 5;

const alertNodeInfo = ({ node, path, treeIndex }) => {
    const objectString = Object.keys(node)
        .map(k => (k === 'children' ? 'children: Array' : `${k}: '${node[k]}'`))
        .join(',\n   ');

    global.alert(
        'Info passed to the button generator:\n\n' +
        `node: {\n   ${objectString}\n},\n` +
        `path: [${path.join(', ')}],\n` +
        `treeIndex: ${treeIndex}`
    );
};

class arbolBusqueda extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            searchString: '',
            searchFocusIndex: 0,
            searchFoundCount: null,
            treeData: [],
            botonesFrm: [
                // {
                //     name: "expandir",
                //     clase: "btn btn-sm pull-right flipInX animated",
                //     evento: this.toggleNodeExpansion.bind(this, true),
                //     leyenda: "",
                //     iclase: faPlus,
                //     tooltip: "Expadir"
                // },
                // {
                //     name: "expandirNo",
                //     clase: "btn btn-sm pull-right flipInX animated",
                //     evento: this.toggleNodeExpansion.bind(this, false),
                //     leyenda: "",
                //     iclase: faMinus,//"fa fa-pencil",
                //     tooltip: "Contraer"
                // },
                {
                    name: "selectPrevMatch",
                    clase: "btn btn-sm pull-right flipInX animated",
                    evento: this.selectPrevMatch,
                    leyenda: "",
                    iclase: faBackward,
                    tooltip: "Anterior"
                },
                {
                    name: "selectNextMatch",
                    clase: "btn btn-sm pull-right flipInX animated",
                    evento: this.selectNextMatch,
                    leyenda: "",
                    iclase: faForward,
                    tooltip: "Siguiente"
                },
            ],
            FrmAttributes: { readOnly: false, focus: false, label: '', float: 'right', hidden: 'unset' },
            BusquedaTxT: { value: "", attributes: { readOnly: false, focus: false, label: ((!props.label) ?  'Cuenta Contable' : props.label), hidden: 'unset', Editando: false, maxLength: "200", placeholder:'Buscar...' } },
        }
    }

    componentDidUpdate = (prevProps, prevState, snapshot) => {
        if (this.props.listatree !== prevProps.listatree) {
            const _treeData = this.props.listatree;
            this.setState({ treeData: _treeData });

        }
    }


    handleTreeOnChange = (treeData) => {

        this.setState({ treeData });
    };

    handleSearchOnChange = e => {
        let _BusquedaTxT = this.state.BusquedaTxT;
        _BusquedaTxT.value =e.target.value;
        this.setState({
            searchString: e.target.value,BusquedaTxT:_BusquedaTxT
        });
    };

    customSearchMethod = ({ node, searchQuery }) =>
        searchQuery && (
            node.title.toLowerCase().indexOf(searchQuery.toLowerCase()) > -1 ||
            node.subtitle.toLowerCase().indexOf(searchQuery.toLowerCase()) > -1);

    selectPrevMatch = () => {
        const { searchFocusIndex, searchFoundCount } = this.state;

        this.setState({
            searchFocusIndex:
                searchFocusIndex !== null
                    ? (searchFoundCount + searchFocusIndex - 1) % searchFoundCount
                    : searchFoundCount - 1,
        });
    };

    selectNextMatch = () => {
        const { searchFocusIndex, searchFoundCount } = this.state;

        this.setState({
            searchFocusIndex:
                searchFocusIndex !== null
                    ? (searchFocusIndex + 1) % searchFoundCount
                    : 0,
        });
    };

    toggleNodeExpansion = expanded => {
        this.setState(prevState => ({
            treeData: toggleExpandedForAll({
                treeData: prevState.treeData,
                expanded,
            }),
        }));
    };
    handleNodeClick = (node) => {
        this.setState({
            nodeClicked: node
        });
    };
    render() {
        const { searchString, searchFocusIndex, searchFoundCount, treeData } = this.state;
        const { col } = this.props
        return (

            <div className={"col-sm-" + col + " col-md-" + col}>
                <div >
                    <div className="row">
                        <div className="col-md-12">
                            <CajaTexto col="10" id="BusquedaTxT" type="text" label={this.state.BusquedaTxT.attributes.label} value={this.state.BusquedaTxT.value} attributes={this.state.BusquedaTxT.attributes} onChangeInput={this.handleSearchOnChange} />
                            <FormBotones col='2'  attributes={this.state.FrmAttributes}  botones={this.state.botonesFrm}/>
                        </div>
                    </div>

                </div>
                <div style={{ height: 300 }}>



                    <SortableTree
                        //lassName= "treeview mantenimiento"
                        treeData={treeData}
                        onChange={this.handleTreeOnChange}
                        onMoveNode={({ node, treeIndex, path }) =>
                            global.console.log(
                                'node:',
                                node,
                                'treeIndex:',
                                treeIndex,
                                'path:',
                                path
                            )
                        }
                        maxDepth={maxDepth}
                        searchMethod={this.customSearchMethod}
                        searchQuery={searchString}
                        searchFocusOffset={searchFocusIndex}
                        canDrag={false}
                        onlyExpandSearchedNodes={true}
                        rowHeight={50}
                        slideRegionSize={20} //100
                        scaffoldBlockPxWidth={32} //44
                        searchFinishCallback={matches =>
                            this.setState({
                                searchFoundCount: matches.length,
                                searchFocusIndex:
                                    matches.length > 0 ? searchFocusIndex % matches.length : 0,
                            })
                        }
                        isVirtualized={true}
                        generateNodeProps={rowInfo => {
                            const { node } = rowInfo;
                            return {

                                onClick: () => {
                                    this.props.onSelectedRow(rowInfo);

                                    this.handleNodeClick(node);
                                },
                                style:
                                    node === this.state.nodeClicked
                                        ? {
                                            color: "#d73220",
                                            //border: "3px solid #d73220",
                                        }
                                        : {}
                            }
                        }}
                        //style={{ width: '100%', height: '80%', overflow: 'hidden', fontSize: '11px' }}
                        style={{ width: '100%', height: '80%' }}
                    />


                </div>

            </div>
        )



    }
}
export default arbolBusqueda;

