import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { Observable } from 'rxjs/Observable';
import { uniqBy as _uniqBy, indexOf as _indexOf } from 'lodash/array';

@Injectable()
export class KnokRollService {
  private items: number[] = [];
  private itemsSubject: ReplaySubject<number[]> = new ReplaySubject<number[]>();

  get itemsObservable(): Observable<number[]> {
    return this.itemsSubject.asObservable().debounceTime(10);
  }

  get length(): number {
    return this.items.length;
  }

  set(items: number | number[]): void {
    if (!Array.isArray(items)) {
      items = [items];
    }
    this.items = _uniqBy(items, parseInt);
    this.itemsSubject.next(this.items);
  }

  get(): number[] {
    return Object.assign([], this.items);
  }

  clean(): void {
    this.items = [];
    this.itemsSubject.next(this.items);
  }

  before(id: number, cycled: boolean = false): number {
    const index: number = _indexOf(this.items, id);
    if (index !== -1) {
        if (index === 0 && cycled) {
          return this.items[this.length - 1];
        } else if (index > 0 && index < this.length) {
          return this.items[index - 1];
        }
    }
    return -1;
  }

  after(id: number, cycled: boolean = false): number {
    const index: number = _indexOf(this.items, id);
    if (index !== -1) {
      if (index === (this.length - 1) && cycled) {
        return this.items[0];
      } else if (index >= 0 && index < (this.length - 1)) {
        return this.items[index + 1];
      }
    }
    return -1;
  }
}
