import { Component, Input, OnInit } from '@angular/core';
import { Dossier, DownloadFileType, IReportTemplate } from '@red/domain';
import { FormBuilder, FormGroup } from '@angular/forms';
import { EditDossierSaveResult, EditDossierSectionInterface } from '../edit-dossier-section.interface';
import { downloadTypesTranslations } from '@translations/download-types-translations';
import { ReportTemplateService } from '@services/report-template.service';
import { PermissionsService } from '@services/permissions.service';
import { firstValueFrom, Observable } from 'rxjs';
import { DossiersService } from '@services/dossiers/dossiers.service';
import { WatermarksMapService } from '@services/entity-services/watermarks-map.service';
import { ContextComponent, shareLast } from '@iqser/common-ui/lib/utils';
import { Roles } from '@users/roles';

interface EditDossierDownloadPackageContext {
    existsWatermarks: boolean;
}

@Component({
    selector: 'redaction-edit-dossier-download-package',
    templateUrl: './edit-dossier-download-package.component.html',
    styleUrls: ['./edit-dossier-download-package.component.scss'],
})
export class EditDossierDownloadPackageComponent
    extends ContextComponent<EditDossierDownloadPackageContext>
    implements OnInit, EditDossierSectionInterface
{
    #existsWatermarks$: Observable<boolean>;
    form: FormGroup;
    downloadTypes: { key: DownloadFileType; label: string }[] = ['ORIGINAL', 'PREVIEW', 'DELTA_PREVIEW', 'REDACTED'].map(
        (type: DownloadFileType) => ({
            key: type,
            label: downloadTypesTranslations[type],
        }),
    );
    availableReportTypes: IReportTemplate[] = [];
    readonly roles = Roles;
    @Input() dossier: Dossier;

    constructor(
        private readonly _dossiersService: DossiersService,
        private readonly _reportTemplateController: ReportTemplateService,
        private readonly _formBuilder: FormBuilder,
        private readonly _permissionsService: PermissionsService,
        private readonly _watermarksMapService: WatermarksMapService,
    ) {
        super();
    }

    get reportTypesLength() {
        return this.form.controls['reportTemplateIds']?.value?.length || 0;
    }

    get downloadFileTypesLength() {
        return this.form.controls['downloadFileTypes']?.value?.length || 0;
    }

    get changed(): boolean {
        if (!this.form) {
            return false;
        }

        for (const key of Object.keys(this.form.getRawValue())) {
            if (key.toLowerCase().includes('watermark')) {
                if (this.dossier[key] !== this.form.get(key).value) {
                    return true;
                }
            } else {
                if (this.dossier[key].length !== this.form.get(key).value.length) {
                    return true;
                }
                const originalItems = [...this.dossier[key]].sort();
                const newItems = [...this.form.get(key).value].sort();

                for (let idx = 0; idx < originalItems.length; ++idx) {
                    if (originalItems[idx] !== newItems[idx]) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    get disabled() {
        return false;
    }

    get valid(): boolean {
        return this.form && this.form.valid;
    }

    get canEditDossier(): boolean {
        return this._permissionsService.canEditDossier(this.dossier);
    }

    reportTemplateValueMapper = (reportTemplate: IReportTemplate) => reportTemplate.templateId;

    async ngOnInit() {
        const dossierTemplateId = this.dossier.dossierTemplateId;

        this.#existsWatermarks$ = this._watermarksMapService.watchChanged$(dossierTemplateId).pipe(shareLast());

        super._initContext({
            existsWatermarks: this.#existsWatermarks$,
        });

        this.availableReportTypes = (await this._reportTemplateController.getAvailableReportTemplates(dossierTemplateId)) || [];

        this.form = this.#getForm();
        if (!this.canEditDossier) {
            this.form.disable();
        }
    }

    async save(): EditDossierSaveResult {
        const dossier = {
            ...this.dossier,
            downloadFileTypes: this.form.get('downloadFileTypes').value,
            reportTemplateIds: this.form.get('reportTemplateIds').value,
            watermarkId: this.form.get('watermarkId').value,
            previewWatermarkId: this.form.get('previewWatermarkId').value,
        };

        const updateDossier = await firstValueFrom(this._dossiersService.createOrUpdate(dossier));
        return { success: !!updateDossier };
    }

    revert() {
        this.form.reset({
            downloadFileTypes: this.dossier.downloadFileTypes,
            reportTemplateIds: this.dossier.reportTemplateIds,
            watermarkId: this.dossier.watermarkId,
            previewWatermarkId: this.dossier.previewWatermarkId,
        });
    }

    #getForm() {
        return this._formBuilder.group(
            {
                reportTemplateIds: [this.dossier.reportTemplateIds],
                downloadFileTypes: [this.dossier.downloadFileTypes],
                watermarkId: [this.dossier.watermarkId],
                previewWatermarkId: [this.dossier.previewWatermarkId],
            },
            {
                validators: control =>
                    control.value.reportTemplateIds?.length > 0 || control.value.downloadFileTypes?.length > 0
                        ? null
                        : { downloadPackage: true },
            },
        );
    }
}
