import { ChangeDetectorRef, Component, HostBinding, Input, OnChanges, OnDestroy } from '@angular/core';
import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { BehaviorSubject, filter, Subscription } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
import { AnnotationsListingService } from '../../services/annotations-listing.service';

@Component({
    selector: 'redaction-annotation-reference [annotation]',
    templateUrl: './annotation-reference.component.html',
})
export class AnnotationReferenceComponent implements OnChanges, OnDestroy {
    @Input() annotation: AnnotationWrapper;
    @HostBinding('class.active') isSelected = false;
    readonly #annotationChanged$ = new BehaviorSubject<AnnotationWrapper>(undefined);
    readonly #subscription: Subscription;

    constructor(private readonly _listingService: AnnotationsListingService, private readonly _changeRef: ChangeDetectorRef) {
        const annotationsChanged$ = this.#annotationChanged$.pipe(
            filter(annotation => !!annotation),
            switchMap(annotation => this._listingService.isSelected$(annotation)),
            tap((isSelected: boolean) => {
                this.isSelected = isSelected;
                this._changeRef.markForCheck();
            }),
        );
        this.#subscription = annotationsChanged$.subscribe();
    }

    ngOnChanges(): void {
        this.#annotationChanged$.next(this.annotation);
    }

    ngOnDestroy(): void {
        this.#subscription.unsubscribe();
    }
}
