import * as React from 'react';

import {
    ComboBox,
    IComboBoxOption,
    Checkbox,
    CommandButton,
    Icon,
    Persona,
    PersonaSize

} from 'office-ui-fabric-react/lib/index';

import "./index.css";
import { OrganizationUnit } from '../../Models';
import { CachingService } from '../../Services';

class ComboBoxOptionWrapper extends React.Component<any, any>{
    public render() {
        return this.props.render();
    }

    // shouldComponentUpdate(newProps){

    // }
}

export class TreeComboBox extends React.Component<any, any> {
    private _comboBox: any;
    private _collapsedNodes: number[] = [];
    private _cachingService = new CachingService();

    constructor(props: {}) {
        super(props);

        this.state = {
            selectedItems: [],
            paddingDirection: this._cachingService.readPersistant('Language') == 1 ? "paddingRight" : "paddingLeft",
            arrowDirection: this._cachingService.readPersistant('Language') == 1 ? "right" : "left"

        };


    }

    componentDidMount() {

        let _this = this;
        setTimeout(function () {

            let indexes: number[] = [];
            if (_this._comboBox) {
                if ((Object.prototype.toString.call(_this.props.value) === "[object Array]")) {
                    _this.props.value.forEach((id: number) => {
                        _this._comboBox.state.currentOptions.forEach((element: any, index: number) => {
                            if (element.id == id)
                                indexes.push(index)
                        });
                    })
                }
                else {
                    _this._comboBox.state.currentOptions.forEach((element: any, index: number) => {
                        if (element.id == _this.props.value)
                            indexes.push(index)
                    });
                }


                _this._comboBox.setState({ 'selectedIndices': indexes })


            }
        }, 1000);

    }

    private _toggleChildTree = (e: any) => {
        e.preventDefault();

        let isCollapsed = true;
        if (e.currentTarget.getAttribute('data-icon-name') == 'CaretSolidDown') {
            e.currentTarget.nextElementSibling.style.display = '';
            e.currentTarget.style.display = 'none';
            isCollapsed = false
        }
        else {
            e.currentTarget.previousElementSibling.style.display = '';
            e.currentTarget.style.display = 'none';
        }

        let index = this._collapsedNodes.indexOf(e.currentTarget.getAttribute('id'));
        if (isCollapsed == true && index > -1) {
            this._collapsedNodes.splice(index, 1)
        }
        else if (isCollapsed == false && index == -1) {
            this._collapsedNodes.push(e.currentTarget.getAttribute('id'))
        }

        // let children = document.getElementsByClassName('parent_' + e.currentTarget.getAttribute('id'));

        // for (let i = 0; i < children.length; i++) {
        //     let child: any = children.item(i)
        //     if (child)
        //         child.style.display = (isCollapsed == false ? 'none' : '');
        // }

        this._toggleCollapsible();

        return false;
    }

    private _toggleCollapsible() {
        let children = document.getElementsByClassName('tree-item');

        for (let i = 0; i < children.length; i++) {

            let child: any = children.item(i)
            if (child) {
                child.style.display = '';

                let childParents = child.getAttribute('parentnodes').split(',');
                for (let j = 0; j < this._collapsedNodes.length; j++) {
                    let node = this._collapsedNodes[j];
                    if (childParents.indexOf(node) > -1)
                        child.style.display = 'none';
                }
            }
        }
    }

    private renderItemLabel(item: any) {

        const personaProps = {
            imageUrl: '',
            text: item.text
        };

        return <Persona
            {...personaProps}

            size={PersonaSize.size28}
            hidePersonaDetails={false}
        />;
    }

    // private _onchangeSelection(item: any, ev?: React.FormEvent<HTMLElement | HTMLInputElement>,
    //     checked?: boolean): void {
    //     let selectedItems = this.state.selectedItems
    //     let itemIndex = selectedItems.indexOf(item.id)

    //     if (checked && itemIndex == -1)
    //         selectedItems.push(item.id);
    //     else if (!checked && itemIndex > -1)
    //         selectedItems.splice(itemIndex, 1);

    //     this._comboBox.setState({
    //         selectedIndices: selectedItems
    //     });

    //     //this.setState({ 'selectedItems': selectedItems, 'options': this._options })
    // }

    private _onRenderItem = (item: any, _onRenderItem: any): JSX.Element => {
        var _this = this;

        //this._toggleCollapsible();

        var _a = this._comboBox.props.onRenderOption, onRenderOption = _a === void 0 ? this._comboBox._onRenderOptionContent : _a;
        var id = this._comboBox._id;
        var isSelected = this._comboBox._isOptionSelected(item.index);

        var isDisabled = this.props.disabledItems && this.props.disabledItems.indexOf(item.key) > -1;

        var optionStyles = this._comboBox._getCurrentOptionStyles(item);
        //debugger;
        let margin = 10 + item.level * 20;
        //var optionClassNames = getComboBoxOptionClassNames(this._comboBox._getCurrentOptionStyles(item));
        var checkboxStyles = function () {

            return optionStyles;
        };
        var title = this._comboBox._getPreviewText(item);
        var getOptionComponent = function () {
            return !_this._comboBox.props.multiSelect ? (
                React.createElement(CommandButton, {
                    id: id + '-list' + item.index, key: item.key,
                    styles: _this._comboBox._getCurrentOptionStyles(item),
                    checked: isSelected,
                    className: 'ms-ComboBox-option',
                    onClick: _this._comboBox._onItemClick(item.index),
                    onMouseEnter: _this._comboBox._onOptionMouseEnter.bind(_this, item.index),
                    onMouseMove: _this._comboBox._onOptionMouseMove.bind(_this, item.index),
                    onMouseLeave: _this._comboBox._onOptionMouseLeave, role: "option",
                    "aria-selected": isSelected ? 'true' : 'false',
                    onRenderChildren: _this.renderItemLabel.bind(_this, item),
                    ariaLabel: _this._comboBox._getPreviewText(item),
                    disabled: item.disabled
                }, ' ',
                    React.createElement("span", { ref: isSelected ? _this._comboBox._selectedElement : undefined },
                        onRenderOption(item, _this._comboBox._onRenderOptionContent)))) :
                (React.createElement(Checkbox, {
                    id: id + '-list' + item.index,
                    ariaLabel: _this._comboBox._getPreviewText(item), key: item.key,
                    styles: checkboxStyles, className: 'ms-ComboBox-option',
                    onChange: _this._comboBox._onItemClick(item.index),
                    label: item.text, role: "option",
                    "aria-selected": isSelected ? 'true' : 'false',
                    checked: isSelected, title: title, disabled: isDisabled,
                    onRenderLabel: _this.renderItemLabel.bind(_this, item)
                }, onRenderOption(item, _this._comboBox._onRenderOptionContent)));
        };
        return ((React.createElement('div', {
            key: item.key, index: item.index,
            parentnodes: item.parents.join(','),
            className: item.parentId == null ? 'tree-item' : 'tree-item parent_' + item.parentId,
            style: { [_this.state.paddingDirection]: margin, position: 'relative' }
        }, (
                item.parent ? (
                    <span style={{ position: 'absolute', [_this.state.arrowDirection]: margin - 5, top: 9, zIndex: 999, cursor: 'pointer' }}>
                        <Icon id={item.id} onClick={_this._toggleChildTree.bind(_this)} style={{ paddingRight: 5, float: 'left' }} iconName="CaretSolidDown" />
                        <Icon id={item.id} onClick={_this._toggleChildTree.bind(_this)} style={{ paddingRight: 5, float: 'left', display: 'none' }} iconName="CaretSolidRight" />
                    </span>
                ) : ''
            ), React.createElement(ComboBoxOptionWrapper, {
                disabled: item.disabled, isSelected: isSelected, text: item.text,
                render: getOptionComponent
            }))));


        // return (
        //     <div style={{ paddingLeft: margin }}
        //         className={item.parentId == null ? 'treeComboBoxItem' : 'treeComboBoxItem parent_' + item.parentId}>
        // {
        //     item.parent && (
        //         <span>
        //             <Icon id={item.id} onClick={this._toggleChildTree} style={{ marginRight: 5, float: 'left' }} iconName="CaretSolidDown" />
        //             <Icon id={item.id} onClick={this._toggleChildTree} style={{ marginRight: 5, float: 'left', display: 'none' }} iconName="CaretSolidRight" />
        //         </span>
        //     )
        // }
        //         <Checkbox onChange={this._onchangeSelection.bind(this, item)} label={item.text} />
        //     </div>
        // )

    }



    private _onOpen() {
        var _this = this;
        setTimeout(() => {
            let list: any = document.getElementById(_this._comboBox._id + "-list");

            list.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.visibility = "visible";
            list.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.background = "rgba(255,255,255,0.4)";

            //debugger;
        }, 100);

    }

    private _onChange(option?: IComboBoxOption, index?: number, value?: string): void {
        //debugger;
        let ids: number[] = [];
        let organizationUnits: OrganizationUnit[] = [];
        if (this._comboBox.state.selectedIndices) {
            this._comboBox.state.selectedIndices.forEach((index: number) => {
                ids.push(this._comboBox.state.currentOptions[index].id);
                organizationUnits.push(this._comboBox.state.currentOptions[index].item);
            })
        }

        if (this.props.onChanged)
            this.props.onChanged(ids, organizationUnits);
    }

    public render() {
        return (
            <div>
                <ComboBox
                    label={this.props.label}
                    required={this.props.required}
                    multiSelect={this.props.multiple}
                    autoComplete="on"
                    defaultSelectedKey={this.props.value}
                    componentRef={(input) => {
                        this._comboBox = input
                        if (this.props.comboboxref)
                            this.props.comboboxref.reference = input
                    }}
                    options={this.props.options}
                    onRenderItem={this._onRenderItem.bind(this)}
                    errorMessage={this.props.errorMessage}
                    useComboBoxAsMenuWidth={true}
                    disabled={this.props.disabled}
                    //styles={{ callout: { background: "red" }, optionsContainer: { background: "red" }, optionsContainerWrapper: { background: "red" } }}
                    onChanged={this._onChange.bind(this)}
                    onMenuOpen={this._onOpen.bind(this)}
                    onRenderLowerContent={this.props.onRenderLowerContent}

                />
            </div>
        );
    }
}

export default TreeComboBox;