import { Predicate, FilterQueryOp } from 'breeze-client';
import { EntityTypeNames } from '../constants/constants';
import { ServiceBase } from '../data/service-base';
import { AgGridView, ViewVisibilityEnum } from '../model/common-model';

export class AgGridViewService extends ServiceBase<AgGridView>{
  constructor() {
    super(EntityTypeNames.AgGridView);
  }

  public async getAllFromModuleId(moduleId: string, currentUserId: number = null, searchName: string = null): Promise<Array<AgGridView>> {
    let p1 = new Predicate('moduleId', FilterQueryOp.Equals, moduleId);
    let pTot = p1;
    if (currentUserId != null) {
      let p2 = new Predicate('visibility', FilterQueryOp.NotEquals, "Private");
      let p3 = new Predicate('visibility', FilterQueryOp.Equals, "Private");
      let p4 = new Predicate('authorId', FilterQueryOp.Equals, currentUserId);
      pTot = pTot.and(p2.or(p3.and(p4)));
      if (searchName) {
        let p5 = new Predicate('name', FilterQueryOp.Contains, searchName);
        pTot = pTot.and(p5);
      }
    }
    let result = await this.getEntities(pTot, ['author'], { $orderby: 'Visibility, Name' });

    return result;
  }

  public async getAllFromModuleIdWithShared(moduleId: string, currentUserId: number = null, searchName: string = null): Promise<Array<AgGridView>> {
    let result = await this.getEntities(null, ['author', 'agGridViewUsers.user'], { moduleId: moduleId, currentUserId: currentUserId, allView: (currentUserId == null), name: searchName, $orderby: 'Visibility, Name' },);

    return result;
  }

  public async getDefaultViewFromModuleId(moduleId: string): Promise<AgGridView> {
    let p1 = new Predicate('moduleId', FilterQueryOp.Equals, moduleId);
    let p2 = new Predicate("isDefaultView", FilterQueryOp.Equals, true);
    let result = await this.firstEntity(p1.and(p2));
    return result;
  }
}
