import { ChangeDetectorRef, Component, ElementRef, Input, OnInit, Optional, ViewChild } from '@angular/core';
import { HelpModeService } from '@iqser/common-ui';
import { Debounce, trackByFactory } from '@iqser/common-ui/lib/utils';
import { Dossier, File, IFileAttributeConfig } from '@red/domain';
import { FileAttributesService } from '@services/entity-services/file-attributes.service';

@Component({
    selector: 'redaction-workflow-item',
    templateUrl: './workflow-item.component.html',
    styleUrls: ['./workflow-item.component.scss'],
})
export class WorkflowItemComponent implements OnInit {
    @ViewChild('actionsWrapper', { static: true }) private _actionsWrapper: ElementRef;
    width: number;
    readonly trackBy = trackByFactory();
    @Input({ required: true }) file: File;
    @Input({ required: true }) dossier: Dossier;
    @Input({ required: true }) displayedAttributes: IFileAttributeConfig[];

    constructor(
        readonly fileAttributesService: FileAttributesService,
        private readonly _changeRef: ChangeDetectorRef,
        @Optional() readonly helpModeService: HelpModeService,
    ) {}

    ngOnInit(): void {
        const _observer = new ResizeObserver((entries: ResizeObserverEntry[]) => {
            this._updateItemWidth(entries[0]);
        });
        _observer.observe(this._actionsWrapper.nativeElement);
    }

    @Debounce(30)
    private _updateItemWidth(entry: ResizeObserverEntry): void {
        this.width = entry.contentRect.width;
        this._changeRef.markForCheck();
    }
}
