import * as i2 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { EventEmitter, Output, Input, Component } from '@angular/core';
import * as i3 from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import * as i4 from '@angular/material/checkbox';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import * as i7 from '@angular/material/progress-bar';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { AgreementStateSelectComponent } from '@aztrix/components/agreement-state-select';
import * as i9 from '@aztrix/components/button';
import { ButtonModule } from '@aztrix/components/button';
import * as i6 from '@aztrix/components/spinner';
import { SpinnerModule } from '@aztrix/components/spinner';
import * as i8 from '@aztrix/components/value-edit';
import { DateEditModule } from '@aztrix/components/value-edit';
import * as i5 from '@aztrix/helpers';
import { proposalTitle, downloadDataAsFile, hasVerification, getStartOfDay, getEndOfDay, HelperPipesModule } from '@aztrix/helpers';
import { AgreementState } from '@aztrix/models';
import * as i1 from '@aztrix/sdk';
import { SearchAgreementsRepresentation } from '@aztrix/sdk';
import { TranslatePipe } from '@aztrix/translate';
import { FormControl, FormGroup } from '@ngneat/reactive-forms';
import { getUnixTime } from 'date-fns';
import { BehaviorSubject, Subscription, startWith, distinctUntilChanged, combineLatest, filter, switchMap, takeWhile, map } from 'rxjs';

class ExportAgreementsComponent {
    constructor(_proposalsService, _changeDetector) {
        this._proposalsService = _proposalsService;
        this._changeDetector = _changeDetector;
        this.done = new EventEmitter();
        this.exporting$ = new BehaviorSubject(undefined);
        this.generating$ = new BehaviorSubject(false);
        this.dateRangeEnabledForm = new FormControl(false);
        this.dateRangeForm = new FormGroup({
            from: new FormControl(),
            to: new FormControl(),
        });
        this.agreementStatusForm = new FormControl(undefined);
        this.agreementConfirmationForm = new FormControl(undefined);
        this.agreementVerificationForm = new FormControl(undefined);
        this.AgreementState = AgreementState;
        this.subscription = new Subscription();
        this.generated = 5000;
        this.agreementStatusChanges$ = this.agreementStatusForm.valueChanges.pipe(startWith(this.agreementStatusForm.value), distinctUntilChanged());
        this.agreementConfirmationChanges$ = this.agreementConfirmationForm.valueChanges.pipe(startWith(this.agreementConfirmationForm.value), distinctUntilChanged());
        this.agreementVerificationChanges$ = this.agreementVerificationForm.valueChanges.pipe(startWith(this.agreementVerificationForm.value), distinctUntilChanged());
    }
    ngOnInit() {
        combineLatest([
            this.agreementStatusChanges$,
            this.agreementConfirmationChanges$,
            this.agreementVerificationChanges$,
        ])
            .pipe(filter(() => !this.dateRangeEnabledForm.value), switchMap(([status, confirmation, verification]) => this._proposalsService.searchAgreementsOfProposal(this.proposal.id || '', {
            agreementStatus: status,
            agreementConfirmation: confirmation,
            agreementVerification: verification,
        })))
            .subscribe((searchResult) => {
            this.total = searchResult.totalNumberOfResults;
        });
        this.dateRangeEnabledForm.valueChanges
            .pipe(startWith(this.dateRangeEnabledForm.value))
            .subscribe((enabled) => {
            if (enabled) {
                this.dateRangeForm.enable();
            }
            else {
                this.dateRangeForm.disable();
            }
        });
    }
    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
    cancel() {
        this.done.emit();
    }
    exportAgreements() {
        this.generating$.next(true);
        const filename = `${proposalTitle(this.proposal)}_agreements.csv`;
        const fromDate = getUnixTime(this.fromDateFrom.value) * 1000 || undefined;
        const toDate = (getUnixTime(this.toDateForm.value) + 24 * 60 * 60) * 1000 || undefined;
        let exportedData = [];
        let exportOngoing = true;
        let headerRow;
        let cursor;
        this.subscription = this.exporting$
            .pipe(takeWhile(() => exportOngoing), switchMap(() => this._proposalsService
            .exportAgreementDataForProposal(this.proposal.id || '', '', this._active(), this._confirmed(), this._verified(), this.dateRangeEnabledForm.value ? fromDate : undefined, this.dateRangeEnabledForm.value ? toDate : undefined, undefined, 5000, cursor || undefined, 'ASCENDING', 'response')
            .pipe(map((data) => {
            cursor = data.headers.get('cursor');
            const dataArray = data.body?.split('\n').filter((d) => d !== '' && !!d);
            headerRow = dataArray?.shift();
            exportedData = [...exportedData, ...(dataArray || [])];
            if ((dataArray?.length || 0) >= 5000) {
                this.generated = this.generated + 5000;
                this._changeDetector.detectChanges();
                this.exporting$.next();
                return null;
            }
            else {
                exportOngoing = false;
                exportedData.unshift(headerRow || '');
                return exportedData;
            }
        }))))
            .subscribe({
            next: (data) => {
                if (data && data.length) {
                    this.generating$.next(false);
                    const joinedData = data.join('\n');
                    downloadDataAsFile(joinedData, filename, 'text/csv');
                    this.done.emit();
                }
            },
            error: () => {
                this.generating$.next(false);
            },
        });
    }
    get hasVerification() {
        return hasVerification(this.proposal);
    }
    get fromDateFrom() {
        return this.dateRangeForm.get('from');
    }
    get toDateForm() {
        return this.dateRangeForm.get('to');
    }
    startOfDay(value) {
        return getStartOfDay(value) || undefined;
    }
    endOfDay(value) {
        return getEndOfDay(value || new Date()) || undefined;
    }
    _active() {
        if (this.agreementStatusForm.value === SearchAgreementsRepresentation.AgreementStatusEnum.ACTIVE) {
            return true;
        }
        if (this.agreementStatusForm.value === SearchAgreementsRepresentation.AgreementStatusEnum.EXPIRED) {
            return false;
        }
        return undefined;
    }
    _confirmed() {
        if (this.agreementConfirmationForm.value ===
            SearchAgreementsRepresentation.AgreementConfirmationEnum.CONFIRMED) {
            return true;
        }
        if (this.agreementConfirmationForm.value ===
            SearchAgreementsRepresentation.AgreementConfirmationEnum.UNCONFIRMED) {
            return false;
        }
        return undefined;
    }
    _verified() {
        if (this.agreementVerificationForm.value) {
            return (this.agreementVerificationForm.value ===
                SearchAgreementsRepresentation.AgreementVerificationEnum.VERIFIED);
        }
        else {
            return undefined;
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: ExportAgreementsComponent, deps: [{ token: i1.ProposalsService }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "17.3.12", type: ExportAgreementsComponent, isStandalone: true, selector: "ax-export-agreements", inputs: { proposal: "proposal" }, outputs: { done: "done" }, ngImport: i0, template: "@if (generating$ | async) {\n  <div class=\"generating\">\n    <p>\n      {{ 'agreements.export.generating' | translate }}\n      @if ((total || 0) > 5000) {\n        <span>{{ generated + '/' + total }}</span>\n      }\n    </p>\n    @if ((total || 0) > 5000) {\n      <mat-progress-bar\n        class=\"progress\"\n        mode=\"determinate\"\n        [value]=\"(generated / (total || 0)) * 100\"\n      >\n      </mat-progress-bar>\n    } @else {\n      <ax-spinner></ax-spinner>\n    }\n  </div>\n} @else {\n  <ax-agreement-state-select\n    [statusForm]=\"agreementStatusForm\"\n    [confirmationForm]=\"agreementConfirmationForm\"\n    [verificationForm]=\"agreementVerificationForm\"\n    [hasVerification]=\"hasVerification\"\n    [outline]=\"true\"\n  ></ax-agreement-state-select>\n\n  <div class=\"date-range\">\n    <mat-checkbox [formControl]=\"dateRangeEnabledForm\"></mat-checkbox>\n    <ax-date-edit\n      class=\"date\"\n      [label]=\"'label.from' | translate\"\n      [form]=\"fromDateFrom\"\n      [maxDate]=\"toDateForm.value\"\n    ></ax-date-edit>\n    <span>-</span>\n    <ax-date-edit\n      class=\"date\"\n      [label]=\"'label.to' | translate\"\n      [form]=\"toDateForm\"\n      [minDate]=\"fromDateFrom.value\"\n    ></ax-date-edit>\n    <div\n      class=\"clicktrap\"\n      *ngIf=\"!dateRangeEnabledForm.value\"\n      (click)=\"dateRangeEnabledForm.setValue(true)\"\n    >\n      &nbsp;\n    </div>\n  </div>\n  @if (dateRangeEnabledForm.value) {\n    @if (!!fromDateFrom.value || (!!fromDateFrom.value && !!toDateForm.value)) {\n      <p>\n        {{\n          'agreements.export.date-range.hint'\n            | translate\n              : {\n                  from: (startOfDay(fromDateFrom.value) | formatDateTime),\n                  to: (endOfDay(toDateForm.value) | formatDateTime)\n                }\n        }}\n      </p>\n    } @else {\n      <p>\n        {{\n          'agreements.export.date-range.hint.to'\n            | translate: {to: (endOfDay(toDateForm.value) | formatDateTime)}\n        }}\n      </p>\n    }\n  }\n\n  <div class=\"h-button-wrapper\">\n    <button axButton (click)=\"cancel()\">{{ 'label.cancel' | translate }}</button>\n    <button axButton color=\"primary\" filled (click)=\"exportAgreements()\">\n      {{ 'group.export.members' | translate }}\n    </button>\n  </div>\n}\n", styles: [":host{display:flex;flex-direction:column;padding:.5rem 1rem}:host .mat-mdc-progress-bar{--mdc-linear-progress-track-color: var(--primary-color-100)}:host p{margin-top:0}.date-range{display:flex;gap:.5rem;margin-bottom:1rem;align-items:center;position:relative}.clicktrap{position:absolute;top:0;left:0;width:100%;height:100%}.generating{display:flex;flex-direction:column;justify-content:center;text-align:center}.progress{margin:1rem 0}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i2.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "pipe", type: i2.AsyncPipe, name: "async" }, { kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i3.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "ngmodule", type: MatFormFieldModule }, { kind: "ngmodule", type: MatSelectModule }, { kind: "ngmodule", type: MatCheckboxModule }, { kind: "component", type: i4.MatCheckbox, selector: "mat-checkbox", inputs: ["aria-label", "aria-labelledby", "aria-describedby", "id", "required", "labelPosition", "name", "value", "disableRipple", "tabIndex", "color", "checked", "disabled", "indeterminate"], outputs: ["change", "indeterminateChange"], exportAs: ["matCheckbox"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i3.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "pipe", type: TranslatePipe, name: "translate" }, { kind: "ngmodule", type: HelperPipesModule }, { kind: "pipe", type: i5.FormatDateTimePipe, name: "formatDateTime" }, { kind: "ngmodule", type: SpinnerModule }, { kind: "component", type: i6.SpinnerComponent, selector: "ax-spinner" }, { kind: "ngmodule", type: MatProgressBarModule }, { kind: "component", type: i7.MatProgressBar, selector: "mat-progress-bar", inputs: ["color", "value", "bufferValue", "mode"], outputs: ["animationEnd"], exportAs: ["matProgressBar"] }, { kind: "component", type: AgreementStateSelectComponent, selector: "ax-agreement-state-select", inputs: ["confirmationForm", "statusForm", "verificationForm", "multiple", "hasVerification", "outline"] }, { kind: "ngmodule", type: DateEditModule }, { kind: "component", type: i8.DateEditComponent, selector: "ax-date-edit", inputs: ["minDate", "maxDate", "startView"] }, { kind: "ngmodule", type: ButtonModule }, { kind: "directive", type: i9.ButtonDirective, selector: "[axButton]", inputs: ["color", "labelHideMobile", "smallButton", "bigButton", "fullWidth", "filled", "outline", "icon-button", "hoverLabel", "hover", "lowercase", "disabled"] }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: ExportAgreementsComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ax-export-agreements', standalone: true, imports: [
                        CommonModule,
                        FormsModule,
                        MatFormFieldModule,
                        MatSelectModule,
                        MatCheckboxModule,
                        ReactiveFormsModule,
                        TranslatePipe,
                        HelperPipesModule,
                        SpinnerModule,
                        MatProgressBarModule,
                        AgreementStateSelectComponent,
                        DateEditModule,
                        ButtonModule,
                    ], template: "@if (generating$ | async) {\n  <div class=\"generating\">\n    <p>\n      {{ 'agreements.export.generating' | translate }}\n      @if ((total || 0) > 5000) {\n        <span>{{ generated + '/' + total }}</span>\n      }\n    </p>\n    @if ((total || 0) > 5000) {\n      <mat-progress-bar\n        class=\"progress\"\n        mode=\"determinate\"\n        [value]=\"(generated / (total || 0)) * 100\"\n      >\n      </mat-progress-bar>\n    } @else {\n      <ax-spinner></ax-spinner>\n    }\n  </div>\n} @else {\n  <ax-agreement-state-select\n    [statusForm]=\"agreementStatusForm\"\n    [confirmationForm]=\"agreementConfirmationForm\"\n    [verificationForm]=\"agreementVerificationForm\"\n    [hasVerification]=\"hasVerification\"\n    [outline]=\"true\"\n  ></ax-agreement-state-select>\n\n  <div class=\"date-range\">\n    <mat-checkbox [formControl]=\"dateRangeEnabledForm\"></mat-checkbox>\n    <ax-date-edit\n      class=\"date\"\n      [label]=\"'label.from' | translate\"\n      [form]=\"fromDateFrom\"\n      [maxDate]=\"toDateForm.value\"\n    ></ax-date-edit>\n    <span>-</span>\n    <ax-date-edit\n      class=\"date\"\n      [label]=\"'label.to' | translate\"\n      [form]=\"toDateForm\"\n      [minDate]=\"fromDateFrom.value\"\n    ></ax-date-edit>\n    <div\n      class=\"clicktrap\"\n      *ngIf=\"!dateRangeEnabledForm.value\"\n      (click)=\"dateRangeEnabledForm.setValue(true)\"\n    >\n      &nbsp;\n    </div>\n  </div>\n  @if (dateRangeEnabledForm.value) {\n    @if (!!fromDateFrom.value || (!!fromDateFrom.value && !!toDateForm.value)) {\n      <p>\n        {{\n          'agreements.export.date-range.hint'\n            | translate\n              : {\n                  from: (startOfDay(fromDateFrom.value) | formatDateTime),\n                  to: (endOfDay(toDateForm.value) | formatDateTime)\n                }\n        }}\n      </p>\n    } @else {\n      <p>\n        {{\n          'agreements.export.date-range.hint.to'\n            | translate: {to: (endOfDay(toDateForm.value) | formatDateTime)}\n        }}\n      </p>\n    }\n  }\n\n  <div class=\"h-button-wrapper\">\n    <button axButton (click)=\"cancel()\">{{ 'label.cancel' | translate }}</button>\n    <button axButton color=\"primary\" filled (click)=\"exportAgreements()\">\n      {{ 'group.export.members' | translate }}\n    </button>\n  </div>\n}\n", styles: [":host{display:flex;flex-direction:column;padding:.5rem 1rem}:host .mat-mdc-progress-bar{--mdc-linear-progress-track-color: var(--primary-color-100)}:host p{margin-top:0}.date-range{display:flex;gap:.5rem;margin-bottom:1rem;align-items:center;position:relative}.clicktrap{position:absolute;top:0;left:0;width:100%;height:100%}.generating{display:flex;flex-direction:column;justify-content:center;text-align:center}.progress{margin:1rem 0}\n"] }]
        }], ctorParameters: () => [{ type: i1.ProposalsService }, { type: i0.ChangeDetectorRef }], propDecorators: { proposal: [{
                type: Input
            }], done: [{
                type: Output
            }] } });

/**
 * Generated bundle index. Do not edit.
 */

export { ExportAgreementsComponent };
//# sourceMappingURL=aztrix-components-export-agreements.mjs.map
