import { customAttribute } from '../decorator/exported';
import { IAttribute, IBindingContext } from '../interface/exported';
import { BindingEngine } from '../binding/exported';
import { connectBehavior } from '../utils/exported';
import { createBindingContext } from '../binding/createBindingContext';

/**
 * uses what ever name it gets with ".trigger" and uses the name as event listener
 *
 */
@customAttribute('#VARIABLE#.trigger')
export class TriggerEventsAttribute implements IAttribute {

    // public
    public $element: HTMLInputElement;
    public $attribute: Attr;
    public $bindingContext: IBindingContext;
    public eventHandlerBinded: any;

    // private
    private expressionValue: string;
    private value: string;
    private name: string;


    /**
     * created
     *
     */
    public created() {
        this.name = this.$attribute.name.replace('.trigger', '');
        this.value = this.$attribute.value;
        this.expressionValue = (this.$attribute as any).value;
        this.eventHandlerBinded = this.eventHandler.bind(this);
        connectBehavior(this.expressionValue, this);
        (this.$element as any).addEventListener(this.name, (this.eventHandlerBinded as EventListenerOrEventListenerObject), false);
    }



    /**
     * attached
     *
     */
    public attached() {
        // nothing atm
    }



    /**
     * detached
     *
     */
    public detached() {
        this.$element.removeEventListener(this.name, this.eventHandlerBinded);
    }



    /**
     * when event triggers it uses the value with ast
     *
     */
    public eventHandler(event: any) {
        BindingEngine.tokenizeParseAndTraverseAST(this.value, createBindingContext(
            this.$bindingContext.$context,
            this.$bindingContext.$overrideContext,
            event
        ));
    }

}
