import { BehaviorSubject } from 'rxjs';
import { Query } from '../models/query';
import { Injectable } from '@angular/core';
import { Sort } from '../models/sort';
import { SORT } from '../enums/sort';

@Injectable({ providedIn: 'root' })
export class QueryService {
  private querySubject = new BehaviorSubject<Query>(new Query({}));
  readonly Query$ = this.querySubject.asObservable();

  constructor() {}

  add(field: string, index: number = -1): void {
    const q = new Query(this.querySubject.value);
    q.fields = q.fields.filter((f: string) => f !== field);
    q.fields.splice(index < 0 ? q.fields.length : index, 0, field);
    this.querySubject.next(q);
  }

  remove(field: string): void {
    const q = new Query(this.querySubject.value);
    q.fields = q.fields.filter((f: string) => f !== field);
    this.querySubject.next(q);
  }

  sort(field: string): void {
    const q = new Query(this.querySubject.value);
    const s = q.sort;
    if (s.field === field) {
      switch (s.dir) {
        case SORT.ASC:
          q.sort = new Sort({ field: field, dir: SORT.DSC });
          break;
        case SORT.DSC:
          q.sort = new Sort({});
          break;
        default:
          q.sort = new Sort({ field: field, dir: SORT.ASC });
          break;
      }
    } else {
      q.sort = new Sort({ field: field, dir: SORT.ASC });
    }
    this.querySubject.next(q);
  }
}
