import { makePropDecorator } from '../../google-decorator-factories';
import { BindDecorator } from '../bind.decorator';

export interface BindPropertyDecorator {
    (settings?: {
        propertyName?: string;
        deserialize?: boolean;
    }): any;
    new(settings?: {
        propertyName?: string;
        deserialize?: boolean;
    }): any;
}

export const Property: BindPropertyDecorator = makePropDecorator('BindProperty', (settings: {
    propertyName?: string;
    deserialize?: boolean;
} = { deserialize: false }) => {
    return ({
        binding: {
            priority: 0,
            bind: ({ properties = {} }, fieldName = settings.propertyName) => {
                if (settings.deserialize && properties[fieldName] !== undefined) {
                    return JSON.parse(properties[fieldName]);
                }

                return properties[fieldName] !== undefined ? properties[fieldName] : properties[settings.propertyName];
            }
        } as BindDecorator
    }) as any;
});
