import {IFactory} from '../../interfaces/components/tree-select/IFactory';
import {IFactory as IComponentsFactory} from '../../interfaces/components/IFactory';
import {Helpers} from '../../../admin/Helpers';
import {ITreeSelect} from '../../interfaces/components/tree-select/ITreeSelect';
import {TreeSelect} from '../../components/tree-select/TreeSelect';
import {IDropdownItem} from '../../interfaces/components/tree-select/IDropdownItem';
import {DropdownItem} from '../../components/tree-select/DropdownItem';
import {IEmbeddedTreeSelect} from '../../interfaces/components/tree-select/IEmbeddedTreeSelect';
import {EmbeddedTreeSelect} from '../../components/tree-select/EmbeddedTreeSelect';

export class Factory implements IFactory {

    protected conf:any;

    protected componentsFactory:IComponentsFactory;

    public setComponentsFactory(factory: IComponentsFactory): void
    {
        this.componentsFactory = factory;
    }

    public init(conf:any): void
    {
        this.conf = {
            treeSelect: null,
            dropdownItem: null,
            embeddedTreeSelect: null,
        };
        Helpers.objectReplaceRecursive(this.conf, conf);
    }

    public createTreeSelect(): ITreeSelect
    {
        let select = this.conf.treeSelect || new TreeSelect();
        select.setDropdownItemCreator(this.createDropdownItem.bind(this));
        return select;
    }

    protected createDropdownItem(treeSelect:ITreeSelect): IDropdownItem
    {
        let item = this.conf.dropdownItem || new DropdownItem(treeSelect);
        item.setSubitemCreator(this.createDropdownItem.bind(this));
        item.setOnClick((item:IDropdownItem)=>{
            if(item.getData().value){
                treeSelect.hideDropdown();
                treeSelect.setValue(item.getData().value);
                treeSelect.setAlias(item.getData().alias || item.getData().value);
            }else{
                item.toggleExpand();
            }
        });
        return item;
    }

    public createEmbeddedTreeSelect(): IEmbeddedTreeSelect
    {
        let select = this.conf.embeddedTreeSelect || new EmbeddedTreeSelect();
        select.setDropdownItemCreator(this.createDropdownItem.bind(this));
        return select;
    }

}