import { NodeType } from '@pilotlab/nodes';
import AttributeBase from '../attributeBase';
import Attributes from '../attributes';
import AttributeRoot from '../attributeRoot';
import Attribute from '../attribute';
import AttributeChangeOptions from '../attributeChangeOptions';
import AttributeEventArgs from '../attributeEventArgs';
import { AttributeChangeActions, DataType } from '../attributeEnums';
import IAttribute from '../interfaces/iAttribute';


export class AttributeSelect
extends AttributeBase<any, AttributeSelect, Attributes, AttributeRoot> {
    constructor(value?:any, label?:string, key?:string, isInitialize:boolean = true) {
        super(Attribute.create, null, DataType.SELECT, label, key, NodeType.COLLECTION, false);

        this.selected = 'none';

        if (isInitialize) this.initialize(value, DataType.SELECT, NodeType.COLLECTION);

        this.attributes.isSignalChange = true;
        this.attributes.changed.listen((args:AttributeEventArgs<any>) => {
            if (args.node.value) {
                this._singleSelect(args.node.key);

                this.selected = args.node.key;
                this.doChanged(AttributeChangeActions.SIGNAL_CHANGE);
            }

        });
    }


    selected:string;


    select(key:string):this {
        this.attributes.get(key).set(true, AttributeChangeOptions.save);
        return this;
    }


    protected _singleSelect(key:string):void {
        for (let i = 0, length = this.attributes.list.size; i < length; i++) {
            const attribute:IAttribute = <IAttribute>this.attributes.list.item(i);
            if (key !== attribute.key) {
                attribute.set(false, AttributeChangeOptions.save);
            }
        }
    }
} // End of class


export default AttributeSelect;
