import { UITreeAction, UITreeNode } from './../ui-tree-model';
export class UITreePanelConfig<TTargetEntity> {
    public id: string = 'id';
    public parentId: string;
    public label: string | ((entry: any) => string);
    public icon: string;
    public withLines: boolean = false;
    public autoExpand: boolean | number = true;
    public isNodeSelectable: (model: TTargetEntity) => boolean;
    public isNodeExpandable: (model: TTargetEntity) => boolean;

    public actions: UITreePanelConfigAction<TTargetEntity>[] = [];

    constructor(init?: Partial<UITreePanelConfig<TTargetEntity>>) {
        Object.assign(this, init);
    }
}

export class UITreePanelConfigAction<TTargetEntity> {
    public label: string | ((entity: TTargetEntity) => string);
    public icon: string;
    public color: string;
    public asDropdown: boolean = true;
    public this: any;
    public fn: (model: TTargetEntity, node: UITreeNode) => void;
    public display: boolean | ((model: TTargetEntity, node: UITreeNode) => boolean);

    constructor(init?: Partial<UITreePanelConfigAction<TTargetEntity>>) {
        Object.assign(this, init);
    }

    public transformToTreeAction(): UITreeAction {
        let action = new UITreeAction({
            label: isFunction(this.label) ? null : this.label,
            generateLabel: isFunction(this.label) ? node => (this.label as any)(node.model as TTargetEntity) : null,
            icon: this.icon,
            color: this.color,
            asDropdown: this.asDropdown,
            this: this.this,
            fn: (node: UITreeNode) => this.fn(node.model as TTargetEntity, node),
        });

        if (this.display == null) {
            action.display = true;
        } else if (typeof this.display == 'boolean') {
            action.display = this.display;
        } else {
            action.display = (node: UITreeNode) => {
                // This if is required because of typing only
                if (isFunction(this.display)) {
                    return this.display(node.model as TTargetEntity, node)
                }
            };
        }

        return action;
    }
}