'use strict';

import {Observable} from 'rxjs';
import {Query} from 'blow-query';
import {IPersistedModelConstructor} from '../interfaces';

export function uniqueFactory(model: IPersistedModelConstructor) {
  return function unique(propertyName): Observable<string> {
    const query = new Query();
    query.equal(propertyName, this[propertyName]);
    return model.count(query.toJSON().where).map(c => {
      if(c === 0) {
        return;
      }
      return `'${propertyName}' does not have unique value`;
    });  
  }
} 