import * as React from "react";
import TreeComboBox from "./TreeComboBox";
import { OrganizationService } from "../Services";
import { OrganizationUnit } from "src/Models";
import { IComboBoxOption } from "office-ui-fabric-react";

export class OrganizationalUnitsTreeComboBox extends React.Component<any, any> {
    private _organizationService: OrganizationService = new OrganizationService();
    private _options: Array<IComboBoxOption> = new Array<IComboBoxOption>()

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

        this.state = {
            options: this._options
        }

        this._loadOrganizationalUnits();
    }

    private _loadOrganizationalUnits() {
        this._organizationService.listOrganizations().then((organizationUnits: OrganizationUnit[]) => {
            this._convertOrgChartToOptions(organizationUnits, 0, []);

            this.setState({ options: this._options })
        });
    }

    private _convertOrgChartToOptions(tree: OrganizationUnit[], level: number, parents: number[]): void {
        tree.forEach(item => {
            let _option: any = {
                "key": item.id,
                "text": item.name, "level": level, "id": item.id,
                'parents': parents,
                "parentId": item.parentOrganizationUnitId,
                "item": item
            };
            if (item.organizationUnits && item.organizationUnits.length > 0) {
                let itemParents = parents.slice(0);
                _option.parent = true;
                this._options.push(_option
                );
                itemParents.push(item.id);
                this._convertOrgChartToOptions(item.organizationUnits, level + 1, itemParents.slice(0))
            }
            else {
                this._options.push(_option);
            }
        })
    }

    public render(): JSX.Element {
        return (
            <div><TreeComboBox
                {...this.props} options={this.state.options}></TreeComboBox>
            </div>
        )
    }
}