import { customAttribute/*, inject*/ } from '../decorator/exported';
import { IAttribute, IBindingContext } from '../interface/exported';
import { BindingEngine } from '../binding/exported';
import { connectBehavior /*,DomEventHandler*/ } from '../utils/exported';
import { createBindingContext } from '../binding/createBindingContext';

/**
 * uses what ever name it gets with ".delegate" and uses the name as event listener
 *
 */
@customAttribute('#VARIABLE#.delegate')
export class DelgateEventsAttribute implements IAttribute {

    public $element: HTMLInputElement;
    public $attribute: Attr;
    public $bindingContext: IBindingContext;
    private value: string;
    private name: string;
    private expressionValue: string;
    public eventHandlerBinded: any;
    // private listerID: number;

    constructor(/*private domEventHandler: DomEventHandler*/) {
        // nothing..
    }

    /**
     * created
     *
     */
    public created() {

        this.name = (this.$attribute as any).name.replace('.delegate', '');
        this.value = (this.$attribute as any).value;
        this.expressionValue = (this.$attribute as any).value;
        this.eventHandlerBinded = this.eventHandler.bind(this);
        connectBehavior(this.expressionValue, this);

        // TODO... this isn't really delegate atm, just trigger really!!
        // Need to make a main listener on body and use capture/bubble
        // this.listerID = this.domEventHandler.listenFor(this.name, this.$element, this.eventHandlerBinded);

        (this.$element as any).addEventListener(this.name, (this.eventHandlerBinded as EventListenerOrEventListenerObject), false);
    }



    /**
     * attached
     *
     */
    public attached() {
        // nothing atm
    }



    /**
     * detached
     *
     */
    public detached() {
        // this.domEventHandler.removeListener(this.listerID);
        this.$element.removeEventListener(this.name, this.eventHandlerBinded);
        // this.domEventHandler = null;
    }



    /**
     * when event triggers it uses the value with ast
     *
     */
    public eventHandler(event: any): void {
        BindingEngine.tokenizeParseAndTraverseAST(this.value, createBindingContext(
            this.$bindingContext.$context,
            this.$bindingContext.$overrideContext,
            event
        ));
    }

}
