import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { shareDistinctLast } from '@iqser/common-ui/lib/utils';

@Injectable()
export class CommentingService {
    private _activeAnnotations = new BehaviorSubject<Set<string>>(new Set<string>());

    /** Annotations with active comments section */
    isActive$(annotationId: string): Observable<boolean> {
        return this._activeAnnotations.pipe(
            map(annotations => annotations.has(annotationId)),
            startWith(false),
            shareDistinctLast(),
        );
    }

    toggle(annotationId: string): void {
        if (this._activeAnnotations.value.has(annotationId)) {
            this._deactivate(annotationId);
        } else {
            this._activate(annotationId);
        }
    }

    private _activate(annotationId: string): void {
        const currentValue = this._activeAnnotations.value;
        const newSet = new Set<string>(currentValue).add(annotationId);
        this._activeAnnotations.next(newSet);
    }

    private _deactivate(annotationId: string): void {
        const currentValue = this._activeAnnotations.value;
        const newSet = new Set<string>(currentValue);
        newSet.delete(annotationId);
        this._activeAnnotations.next(newSet);
    }
}
