import { Component, OnDestroy } from '@angular/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { ListingComponent, listingProvidersFactory, LoadingService, TableColumnConfig } from '@iqser/common-ui';
import { DownloadStatus } from '@red/domain';
import { RouterHistoryService } from '@services/router-history.service';
import { FileDownloadService } from '@upload-download/services/file-download.service';
import { firstValueFrom } from 'rxjs';

@Component({
    templateUrl: './downloads-list-screen.component.html',
    styleUrls: ['./downloads-list-screen.component.scss'],
    providers: listingProvidersFactory<DownloadStatus>({
        entitiesService: FileDownloadService,
        component: DownloadsListScreenComponent,
    }),
})
export class DownloadsListScreenComponent extends ListingComponent<DownloadStatus> implements OnDestroy {
    readonly #interval: number;
    readonly tableHeaderLabel = _('downloads-list.table-header.title');
    readonly tableColumnConfigs: TableColumnConfig<DownloadStatus>[] = [
        { label: _('downloads-list.table-col-names.name'), width: '2fr' },
        { label: _('downloads-list.table-col-names.size') },
        { label: _('downloads-list.table-col-names.date') },
        { label: _('downloads-list.table-col-names.status') },
    ];

    constructor(
        private readonly _loadingService: LoadingService,
        readonly fileDownloadService: FileDownloadService,
        readonly routerHistoryService: RouterHistoryService,
    ) {
        super();
        this._loadingService.loadWhile(this._loadData());
        this.#interval = window.setInterval(() => this._loadData(), 5000);
    }

    ngOnDestroy() {
        window.clearInterval(this.#interval);
    }

    downloadItem(download: DownloadStatus) {
        this._loadingService.loadWhile(this.fileDownloadService.performDownload(download));
    }

    deleteItems(downloads?: DownloadStatus[]) {
        this._loadingService.loadWhile(this._deleteItems(downloads));
    }

    private async _deleteItems(downloads?: DownloadStatus[]) {
        const storageIds = (downloads || this.listingService.selected).map(d => d.storageId);
        await firstValueFrom(this.fileDownloadService.delete({ storageIds }));
        await this._loadData();
    }

    private async _loadData() {
        await firstValueFrom(this.fileDownloadService.loadAll());
    }
}
