import { ClassArrayObserverCreator } from './classArrayObserverCreator';
import { IListener, IBindingContext } from '../../interface/exported';

/**
 * Register/creates a array observer with expression
 * It be called on changes and then calls listener
 *
 */
export class ArrayObserverHandler {
    private context: IBindingContext;
    private observing: boolean;


    constructor(
        private expression: string,
        private listener: IListener
    ) {
        this.expression = expression;
        this.listener = listener;
    }



    /**
     * binds observer handler to passed in context
     *
     */
    public bind(context: IBindingContext) {
        this.observing = true;
        this.context = context;
        ClassArrayObserverCreator.create(this.context, this.expression, this);
    }



    /**
     * Gets called by observer, it then calls the listener
     *
     */
    public update(data: any) {
        if (this.listener) {
            this.listener.call(data);
        }
        this.bind(this.context);
    }


    /**
     * Unbinds and clears all internals
     *
     */
    public unbind() {

        // if observing remove observer
        if (this.observing) {
            ClassArrayObserverCreator.remove(this.context, this.expression, this);
        }

        // remove this from caller
        this.listener.caller = null;

        // remove rest of internals
        // todo: Do I need to do this, Im I making grabage collection worse?
        this.listener = null;
        this.observing = false;
        this.context = null;
        this.expression = null;
    }

}
