import { customAttribute } from '../decorator/exported';
import { IAttribute, IListener, IBindingContext } from '../interface/exported';
import { BindingEngine } from '../binding/exported';

/**
 * Helper for selects, so it knows where it is
 *
 */
@customAttribute('model.bind')
export class ModelAttribute implements IAttribute {

    // build in properties added by our template engine
    public $element: HTMLInputElement;
    public $attribute: Attr;
    public $bindingContext: IBindingContext;
    private value: string | null | undefined;
    private subscribeInternal: IListener;
    private expression: string | null | undefined;


    /**
     * created
     *
     */
    public created() {

        (this.$attribute as any).getContent = () => {
            return this;
        };
        this.expression = this.$attribute.value;

        this.subscribeInternal = {
            name: 'modelAttribute:',
            value: this.value,
            call: (newValue: any, oldValue: any) => {
                if (oldValue !== newValue) {
                    this.value = newValue;
                }
            }
        };
        BindingEngine.subscribeClassProperty(this.$bindingContext, this.expression, this.subscribeInternal);

    }


    /**
     * detached
     *
     */
    public detached() {

        (this.$attribute as any).getContent = null;
    }

}
