import { AttributeName } from './NameTypes';

export class AttributeProxy<T, S extends Xrm.Attributes.Attribute, U extends Xrm.Controls.Control> {
    constructor(private _xrm: Xrm.XrmStatic, private _attributeName: AttributeName) { }

    get LogicalName() {
        return this._attributeName.name;
    }

    get Attribute(): S {
        let attribute: S | undefined = this._xrm.Page.getAttribute<S>(this._attributeName.name);
        if(attribute === undefined) {
            console.log(`GetAttribute: No attribute with name '${this._attributeName.name}' available on current form!`);
        }
        return attribute;
    }

    get Control(): U {
        let control: U | undefined = this._xrm.Page.getControl<U>(this._attributeName.name);
        if(control === undefined) {
            console.log(`GetControl: No attribute control with name '${this._attributeName.name}' available on current form!`);
        }
        return control;
    }

    get Value(): T | undefined {
        let value: T | undefined;
        if(this._xrm.Page.getAttribute(this._attributeName.name) !== undefined) {
            value = <T | undefined>this._xrm.Page.getAttribute(this._attributeName.name).getValue();
        }
        else {
            console.log(`Get: No attribute with name '${this._attributeName.name}' available on current form!`);
        }
        return value;
    }

    set Value(value: T | undefined) {
        if(this._xrm.Page.getAttribute(this._attributeName.name) !== undefined) {
            this._xrm.Page.getAttribute(this._attributeName.name).setValue(value);
        }
        else {
            console.log(`Set: No attribute with name '${this._attributeName.name}' available on current form!`);
        }
    }
}