import { CONSTANTS, IElement, IAttribute } from '../interface/exported';
import { unSubscribeClassProperty } from './property/unSubscribeClassProperty';


/**
 * unsubscribe class observables/meta binding
 *
 */
export function unSubscribeClassMetaBinding(_class: IElement | IAttribute) {
    const META = (<any>_class).__proto__[CONSTANTS.META_BINDABLE];
    if (META) {
        const keys = Object.keys(META);
        for (const key of keys) {

            // save key
            const CLASSMETA = (_class as any).__metaBinding[key];
            const subscribeInternal = CLASSMETA.options.subscribeInternal;

            // if it exist unsubscribe
            if (subscribeInternal) {
                unSubscribeClassProperty(_class.$bindingContext, subscribeInternal);
            }

            // get old
            const subscribeExternal = CLASSMETA.options.subscribeExternal;

            // if it exist unsubscribe
            if (_class.$bindingContext && subscribeExternal) {
                if (_class.$element) {
                    const el = _class.$element as Element;
                    const att = `${META[key].options.attribute}.bind`;
                    const attrValue = el.getAttribute(att);
                    if (attrValue) {
                        unSubscribeClassProperty(_class.$bindingContext, subscribeExternal);
                    }
                }
            }

        }
    }
}
