import { ManyToManyRelationHelper } from '../model/relation-helper';
import { Parser, valueConverter } from "aurelia-binding";
import { autoinject } from "aurelia-framework";
import * as breeze from 'breeze-client';

@autoinject
@valueConverter("manyToMany")
export class ManyToManyValueConverter {
  constructor(private parser: Parser) {
  }
  toView(value: any, propertyExpression: string, createTagFnOrStr?: string | ((value: string) => breeze.Entity), propertyTarget?: string): any {
    if (isEmpty(value)) {
      console.warn('ManyToManyValueConverter: Cannot use ManyToMany value converter without an instance of an object');
      return;
    }
    if (isEmpty(propertyExpression)) {
      console.warn('ManyToManyValueConverter: You must specify a property expression parameter.');
      return;
    }
    let entity = value as breeze.Entity;
    let helperName = '__' + propertyExpression + 'Helper';
    if (Object.keys(value).indexOf(helperName) < 0) {
      value[helperName] = new ManyToManyRelationHelper(entity, propertyExpression, createTagFnOrStr, propertyTarget);
    } else if (value[helperName] instanceof ManyToManyRelationHelper) {
      (value[helperName] as ManyToManyRelationHelper<any, any>).initializeData(value[helperName]);
    }
    let getExp = this.parser.parse(helperName + '.selectedEntitiesId');
    return getExp.evaluate({ bindingContext: value, overrideContext: null });
  }
}
