import { Component, EventEmitter, Output, ViewChild, } from '@angular/core';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
import { VotingVisibility } from 'stream-chat';
import { atLeastOneOption, maximumNumberOfVotes } from './validators';
import * as i0 from "@angular/core";
import * as i1 from "../../custom-templates.service";
import * as i2 from "../../chat-client.service";
import * as i3 from "../../notification.service";
import * as i4 from "@angular/common";
import * as i5 from "../../modal/modal.component";
import * as i6 from "../../notification-list/notification-list.component";
import * as i7 from "@angular/forms";
import * as i8 from "@ngx-translate/core";
/**
 *
 */
export class PollComposerComponent {
    constructor(customTemplatesService, chatService, notificationService) {
        this.customTemplatesService = customTemplatesService;
        this.chatService = chatService;
        this.notificationService = notificationService;
        /**
         * Emitted when a poll is created, the poll id is emitted
         */
        this.pollCompose = new EventEmitter();
        /**
         * Emitted when the poll composing is cancelled
         */
        this.cancel = new EventEmitter();
        this.formGroup = new FormGroup({
            name: new FormControl('', [Validators.required]),
            options: new FormArray([new FormControl('')], [atLeastOneOption()]),
            multiple_answers: new FormControl(false),
            maximum_number_of_votes: new FormControl(null, [
                Validators.min(2),
                Validators.max(10),
            ]),
            is_anonymous: new FormControl(false),
            allow_user_suggested_options: new FormControl(false),
            allow_answers: new FormControl(false),
        });
        this.isModalOpen = true;
        this.formGroup
            .get('maximum_number_of_votes')
            ?.addValidators([
            maximumNumberOfVotes(this.formGroup.get('multiple_answers')),
        ]);
        this.formGroup.get('maximum_number_of_votes')?.disable();
        this.formGroup.valueChanges.subscribe((value) => {
            if (value.multiple_answers &&
                this.formGroup.get('maximum_number_of_votes')?.disabled) {
                this.formGroup.get('maximum_number_of_votes')?.enable();
            }
            else if (!value.multiple_answers &&
                this.formGroup.get('maximum_number_of_votes')?.enabled) {
                this.formGroup.get('maximum_number_of_votes')?.disable();
            }
        });
    }
    optionChanged(index) {
        const control = this.options.at(index);
        const penultimateIndex = this.options.length - 2;
        if (index === this.options.length - 1 && control.value?.length === 1) {
            this.addOption();
        }
        else if (index === penultimateIndex &&
            control.value?.length === 0 &&
            this.options.at(this.options.length - 1).value?.length === 0) {
            this.removeLastOption();
        }
    }
    get options() {
        return this.formGroup.get('options');
    }
    addOption() {
        const control = new FormControl('', []);
        this.options.push(control);
    }
    removeLastOption() {
        this.options.removeAt(this.options.length - 1);
    }
    getModalContext() {
        return {
            isOpen: this.isModalOpen,
            isOpenChangeHandler: (isOpen) => {
                if (!isOpen) {
                    this.cancel.emit();
                }
                this.isModalOpen = isOpen;
            },
            content: this.formContent,
        };
    }
    async createPoll() {
        try {
            const maxVotesControl = this.formGroup.get('maximum_number_of_votes');
            const response = await this.chatService.chatClient.polls.createPoll({
                name: this.formGroup.get('name').value,
                options: this.formGroup
                    .get('options')
                    .value.filter((v) => !!v)
                    .map((v) => ({ text: v })),
                enforce_unique_vote: !this.formGroup.get('multiple_answers')?.value,
                max_votes_allowed: maxVotesControl?.value
                    ? +maxVotesControl.value
                    : undefined,
                voting_visibility: this.formGroup.get('is_anonymous')?.value
                    ? VotingVisibility.anonymous
                    : VotingVisibility.public,
                allow_user_suggested_options: !!this.formGroup.get('allow_user_suggested_options')?.value,
                allow_answers: !!this.formGroup.get('allow_answers')?.value,
            });
            this.pollCompose.emit(response?.id);
        }
        catch (error) {
            this.notificationService.addTemporaryNotification('streamChat.Failed to create poll');
            throw error;
        }
    }
}
PollComposerComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.4", ngImport: i0, type: PollComposerComponent, deps: [{ token: i1.CustomTemplatesService }, { token: i2.ChatClientService }, { token: i3.NotificationService }], target: i0.ɵɵFactoryTarget.Component });
PollComposerComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.0.4", type: PollComposerComponent, selector: "stream-poll-composer", outputs: { pollCompose: "pollCompose", cancel: "cancel" }, viewQueries: [{ propertyName: "formContent", first: true, predicate: ["formContent"], descendants: true }], ngImport: i0, template: "<ng-container>\n  <ng-container\n    *ngTemplateOutlet=\"\n      (customTemplatesService.modalTemplate$ | async) || defaultModal;\n      context: getModalContext()\n    \"\n  ></ng-container>\n</ng-container>\n\n<ng-template\n  #defaultModal\n  let-isOpen=\"isOpen\"\n  let-isOpenChangeHandler=\"isOpenChangeHandler\"\n  let-content=\"content\"\n>\n  <stream-modal\n    class=\"str-chat-angular__create-poll-modal str-chat__create-poll-modal\"\n    [isOpen]=\"isOpen\"\n    [content]=\"content\"\n    (isOpenChange)=\"isOpenChangeHandler($event)\"\n  >\n  </stream-modal>\n</ng-template>\n\n<ng-template #formContent>\n  <div\n    class=\"str-chat__dialog str-chat__poll-creation-dialog\"\n    data-testid=\"poll-creation-dialog\"\n  >\n    <div class=\"str-chat__modal-header\">\n      <div class=\"str-chat__modal-header__title\">\n        {{ \"streamChat.Create poll\" | translate }}\n      </div>\n    </div>\n    <div class=\"str-chat__dialog__body\">\n      <form [formGroup]=\"formGroup\" autocomplete=\"off\">\n        <div\n          class=\"str-chat__form__field str-chat__form__input-field str-chat__form__input-field--with-label\"\n          [class.str-chat__form__input-field--has-error]=\"\n            formGroup.get('name')?.errors && formGroup.get('name')?.touched\n          \"\n        >\n          <label class=\"str-chat__form__field-label\" htmlFor=\"name\">\n            {{ \"streamChat.Question\" | translate }}\n          </label>\n          <div class=\"str-chat__form__input-field__value\">\n            <div\n              class=\"str-chat__form-field-error str-chat__form__input-field__error\"\n            >\n              {{\n                (formGroup.get(\"name\")?.errors?.required &&\n                formGroup.get(\"name\")?.touched\n                  ? \"streamChat.Question is required\"\n                  : \"\"\n                ) | translate\n              }}\n            </div>\n            <input\n              id=\"name\"\n              type=\"text\"\n              formControlName=\"name\"\n              placeholder=\"{{ 'streamChat.Ask a question' | translate }}\"\n            />\n          </div>\n        </div>\n        <fieldset class=\"str-chat__form__field str-chat__form__input-fieldset\">\n          <legend class=\"str-chat__form__field-label\">\n            {{ \"streamChat.Options\" | translate }}\n          </legend>\n          <div\n            class=\"str-chat__form-field-error str-chat__form__input-field__error\"\n          >\n            {{\n              (formGroup.get(\"options\")?.errors?.atLeastOne &&\n              formGroup.get(\"options\")?.touched\n                ? \"streamChat.Provide at least one option\"\n                : \"\"\n              ) | translate\n            }}\n          </div>\n          <ng-container formArrayName=\"options\">\n            <div class=\"str-chat__form__input-fieldset__values\">\n              <!-- eslint-disable @angular-eslint/template/use-track-by-function -->\n              <ng-container\n                *ngFor=\"let option of options.controls; let i = index\"\n              >\n                <!-- eslint-enable @angular-eslint/template/use-track-by-function -->\n                <div class=\"str-chat__drag-and-drop-container__item\">\n                  <div class=\"str-chat__form__input-field\">\n                    <input\n                      id=\"option{{ i }}\"\n                      name=\"option{{ i }}\"\n                      type=\"text\"\n                      [formControl]=\"option\"\n                      (input)=\"optionChanged(i)\"\n                      placeholder=\"{{ 'streamChat.Add an option' | translate }}\"\n                    />\n                  </div>\n                </div>\n              </ng-container>\n            </div>\n          </ng-container>\n        </fieldset>\n        <ng-container\n          *ngTemplateOutlet=\"\n            switch;\n            context: {\n              name: 'multiple_answers',\n              control: formGroup.get('multiple_answers'),\n              label: 'streamChat.Multiple answers' | translate\n            }\n          \"\n        ></ng-container>\n        <div\n          *ngIf=\"formGroup.get('multiple_answers')?.value\"\n          class=\"str-chat__form__field str-chat__form__input-field str-chat__form__input-field--with-label\"\n          [class.str-chat__form__input-field--has-error]=\"\n            formGroup.get('maximum_number_of_votes')?.errors &&\n            formGroup.get('maximum_number_of_votes')?.touched\n          \"\n        >\n          <label class=\"str-chat__form__field-label\" htmlFor=\"name\">\n            {{ \"streamChat.Maximum number of votes\" | translate }}\n          </label>\n          <div class=\"str-chat__form__input-field__value\">\n            <div\n              class=\"str-chat__form-field-error str-chat__form__input-field__error\"\n            >\n              {{\n                (formGroup.get(\"maximum_number_of_votes\")?.errors &&\n                formGroup.get(\"maximum_number_of_votes\")?.touched\n                  ? \"streamChat.Provide a value between {{ min }}\n              and {{ max }}\" : \"\" ) | translate: { min: 2, max: 10 } }}\n            </div>\n            <input\n              id=\"maximum_number_of_votes\"\n              type=\"text\"\n              formControlName=\"maximum_number_of_votes\"\n              placeholder=\"{{ 'streamChat.Provide a value between ' \n              + '{{ min }} and {{ max }}' | translate: { min: 2, max: 10 } }}\"\n            />\n          </div>\n        </div>\n        <ng-container\n          *ngTemplateOutlet=\"\n            switch;\n            context: {\n              name: 'is_anonymous',\n              control: formGroup.get('is_anonymous'),\n              label: 'streamChat.Anonymous poll' | translate\n            }\n          \"\n        ></ng-container>\n        <ng-container\n          *ngTemplateOutlet=\"\n            switch;\n            context: {\n              name: 'allow_user_suggested_options',\n              control: formGroup.get('allow_user_suggested_options'),\n              label: 'streamChat.Allow option suggestions' | translate\n            }\n          \"\n        ></ng-container>\n        <ng-container\n          *ngTemplateOutlet=\"\n            switch;\n            context: {\n              name: 'allow_answers',\n              control: formGroup.get('allow_answers'),\n              label: 'streamChat.Allow comments' | translate\n            }\n          \"\n        ></ng-container>\n      </form>\n    </div>\n    <stream-notification-list></stream-notification-list>\n    <div class=\"str-chat__dialog__controls\">\n      <button\n        class=\"str-chat__dialog__controls-button str-chat__dialog__controls-button--cancel\"\n        (click)=\"cancel.emit()\"\n        type=\"button\"\n      >\n        {{ \"streamChat.Cancel\" | translate }}\n      </button>\n      <button\n        class=\"str-chat__dialog__controls-button str-chat__dialog__controls-button--submit\"\n        (click)=\"createPoll()\"\n        [disabled]=\"formGroup.invalid\"\n        type=\"submit\"\n      >\n        {{ \"streamChat.Create\" | translate }}\n      </button>\n    </div>\n  </div>\n</ng-template>\n\n<ng-template #switch let-control=\"control\" let-label=\"label\" let-name=\"name\">\n  <div class=\"str-chat__form__field str-chat__form__switch-field\">\n    <label>\n      <div class=\"str-chat__form__field str-chat__form__switch-field-content\">\n        <div class=\"str-chat__form__field str-chat__form__switch-field__text\">\n          {{ label | translate }}\n        </div>\n      </div>\n      <input\n        type=\"checkbox\"\n        [checked]=\"control.value\"\n        id=\"{{ name }}\"\n        name=\"{{ name }}\"\n      />\n      <div\n        class=\"str-chat__form__switch-field__switch\"\n        [class.str-chat__form__switch-field__switch--on]=\"control.value\"\n        (click)=\"control.setValue(!control.value, { emitEvent: true })\"\n        (keyup.enter)=\"control.setValue(!control.value, { emitEvent: true })\"\n      >\n        <div class=\"str-chat__form__switch-field__switch-handle\"></div>\n      </div>\n    </label>\n  </div>\n</ng-template>\n", dependencies: [{ kind: "directive", type: i4.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i4.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i4.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "component", type: i5.ModalComponent, selector: "stream-modal", inputs: ["isOpen", "content"], outputs: ["isOpenChange"] }, { kind: "component", type: i6.NotificationListComponent, selector: "stream-notification-list" }, { kind: "directive", type: i7.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i7.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i7.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i7.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i7.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "directive", type: i7.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i7.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "directive", type: i7.FormArrayName, selector: "[formArrayName]", inputs: ["formArrayName"] }, { kind: "pipe", type: i4.AsyncPipe, name: "async" }, { kind: "pipe", type: i8.TranslatePipe, name: "translate" }] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.4", ngImport: i0, type: PollComposerComponent, decorators: [{
            type: Component,
            args: [{ selector: 'stream-poll-composer', template: "<ng-container>\n  <ng-container\n    *ngTemplateOutlet=\"\n      (customTemplatesService.modalTemplate$ | async) || defaultModal;\n      context: getModalContext()\n    \"\n  ></ng-container>\n</ng-container>\n\n<ng-template\n  #defaultModal\n  let-isOpen=\"isOpen\"\n  let-isOpenChangeHandler=\"isOpenChangeHandler\"\n  let-content=\"content\"\n>\n  <stream-modal\n    class=\"str-chat-angular__create-poll-modal str-chat__create-poll-modal\"\n    [isOpen]=\"isOpen\"\n    [content]=\"content\"\n    (isOpenChange)=\"isOpenChangeHandler($event)\"\n  >\n  </stream-modal>\n</ng-template>\n\n<ng-template #formContent>\n  <div\n    class=\"str-chat__dialog str-chat__poll-creation-dialog\"\n    data-testid=\"poll-creation-dialog\"\n  >\n    <div class=\"str-chat__modal-header\">\n      <div class=\"str-chat__modal-header__title\">\n        {{ \"streamChat.Create poll\" | translate }}\n      </div>\n    </div>\n    <div class=\"str-chat__dialog__body\">\n      <form [formGroup]=\"formGroup\" autocomplete=\"off\">\n        <div\n          class=\"str-chat__form__field str-chat__form__input-field str-chat__form__input-field--with-label\"\n          [class.str-chat__form__input-field--has-error]=\"\n            formGroup.get('name')?.errors && formGroup.get('name')?.touched\n          \"\n        >\n          <label class=\"str-chat__form__field-label\" htmlFor=\"name\">\n            {{ \"streamChat.Question\" | translate }}\n          </label>\n          <div class=\"str-chat__form__input-field__value\">\n            <div\n              class=\"str-chat__form-field-error str-chat__form__input-field__error\"\n            >\n              {{\n                (formGroup.get(\"name\")?.errors?.required &&\n                formGroup.get(\"name\")?.touched\n                  ? \"streamChat.Question is required\"\n                  : \"\"\n                ) | translate\n              }}\n            </div>\n            <input\n              id=\"name\"\n              type=\"text\"\n              formControlName=\"name\"\n              placeholder=\"{{ 'streamChat.Ask a question' | translate }}\"\n            />\n          </div>\n        </div>\n        <fieldset class=\"str-chat__form__field str-chat__form__input-fieldset\">\n          <legend class=\"str-chat__form__field-label\">\n            {{ \"streamChat.Options\" | translate }}\n          </legend>\n          <div\n            class=\"str-chat__form-field-error str-chat__form__input-field__error\"\n          >\n            {{\n              (formGroup.get(\"options\")?.errors?.atLeastOne &&\n              formGroup.get(\"options\")?.touched\n                ? \"streamChat.Provide at least one option\"\n                : \"\"\n              ) | translate\n            }}\n          </div>\n          <ng-container formArrayName=\"options\">\n            <div class=\"str-chat__form__input-fieldset__values\">\n              <!-- eslint-disable @angular-eslint/template/use-track-by-function -->\n              <ng-container\n                *ngFor=\"let option of options.controls; let i = index\"\n              >\n                <!-- eslint-enable @angular-eslint/template/use-track-by-function -->\n                <div class=\"str-chat__drag-and-drop-container__item\">\n                  <div class=\"str-chat__form__input-field\">\n                    <input\n                      id=\"option{{ i }}\"\n                      name=\"option{{ i }}\"\n                      type=\"text\"\n                      [formControl]=\"option\"\n                      (input)=\"optionChanged(i)\"\n                      placeholder=\"{{ 'streamChat.Add an option' | translate }}\"\n                    />\n                  </div>\n                </div>\n              </ng-container>\n            </div>\n          </ng-container>\n        </fieldset>\n        <ng-container\n          *ngTemplateOutlet=\"\n            switch;\n            context: {\n              name: 'multiple_answers',\n              control: formGroup.get('multiple_answers'),\n              label: 'streamChat.Multiple answers' | translate\n            }\n          \"\n        ></ng-container>\n        <div\n          *ngIf=\"formGroup.get('multiple_answers')?.value\"\n          class=\"str-chat__form__field str-chat__form__input-field str-chat__form__input-field--with-label\"\n          [class.str-chat__form__input-field--has-error]=\"\n            formGroup.get('maximum_number_of_votes')?.errors &&\n            formGroup.get('maximum_number_of_votes')?.touched\n          \"\n        >\n          <label class=\"str-chat__form__field-label\" htmlFor=\"name\">\n            {{ \"streamChat.Maximum number of votes\" | translate }}\n          </label>\n          <div class=\"str-chat__form__input-field__value\">\n            <div\n              class=\"str-chat__form-field-error str-chat__form__input-field__error\"\n            >\n              {{\n                (formGroup.get(\"maximum_number_of_votes\")?.errors &&\n                formGroup.get(\"maximum_number_of_votes\")?.touched\n                  ? \"streamChat.Provide a value between {{ min }}\n              and {{ max }}\" : \"\" ) | translate: { min: 2, max: 10 } }}\n            </div>\n            <input\n              id=\"maximum_number_of_votes\"\n              type=\"text\"\n              formControlName=\"maximum_number_of_votes\"\n              placeholder=\"{{ 'streamChat.Provide a value between ' \n              + '{{ min }} and {{ max }}' | translate: { min: 2, max: 10 } }}\"\n            />\n          </div>\n        </div>\n        <ng-container\n          *ngTemplateOutlet=\"\n            switch;\n            context: {\n              name: 'is_anonymous',\n              control: formGroup.get('is_anonymous'),\n              label: 'streamChat.Anonymous poll' | translate\n            }\n          \"\n        ></ng-container>\n        <ng-container\n          *ngTemplateOutlet=\"\n            switch;\n            context: {\n              name: 'allow_user_suggested_options',\n              control: formGroup.get('allow_user_suggested_options'),\n              label: 'streamChat.Allow option suggestions' | translate\n            }\n          \"\n        ></ng-container>\n        <ng-container\n          *ngTemplateOutlet=\"\n            switch;\n            context: {\n              name: 'allow_answers',\n              control: formGroup.get('allow_answers'),\n              label: 'streamChat.Allow comments' | translate\n            }\n          \"\n        ></ng-container>\n      </form>\n    </div>\n    <stream-notification-list></stream-notification-list>\n    <div class=\"str-chat__dialog__controls\">\n      <button\n        class=\"str-chat__dialog__controls-button str-chat__dialog__controls-button--cancel\"\n        (click)=\"cancel.emit()\"\n        type=\"button\"\n      >\n        {{ \"streamChat.Cancel\" | translate }}\n      </button>\n      <button\n        class=\"str-chat__dialog__controls-button str-chat__dialog__controls-button--submit\"\n        (click)=\"createPoll()\"\n        [disabled]=\"formGroup.invalid\"\n        type=\"submit\"\n      >\n        {{ \"streamChat.Create\" | translate }}\n      </button>\n    </div>\n  </div>\n</ng-template>\n\n<ng-template #switch let-control=\"control\" let-label=\"label\" let-name=\"name\">\n  <div class=\"str-chat__form__field str-chat__form__switch-field\">\n    <label>\n      <div class=\"str-chat__form__field str-chat__form__switch-field-content\">\n        <div class=\"str-chat__form__field str-chat__form__switch-field__text\">\n          {{ label | translate }}\n        </div>\n      </div>\n      <input\n        type=\"checkbox\"\n        [checked]=\"control.value\"\n        id=\"{{ name }}\"\n        name=\"{{ name }}\"\n      />\n      <div\n        class=\"str-chat__form__switch-field__switch\"\n        [class.str-chat__form__switch-field__switch--on]=\"control.value\"\n        (click)=\"control.setValue(!control.value, { emitEvent: true })\"\n        (keyup.enter)=\"control.setValue(!control.value, { emitEvent: true })\"\n      >\n        <div class=\"str-chat__form__switch-field__switch-handle\"></div>\n      </div>\n    </label>\n  </div>\n</ng-template>\n" }]
        }], ctorParameters: function () { return [{ type: i1.CustomTemplatesService }, { type: i2.ChatClientService }, { type: i3.NotificationService }]; }, propDecorators: { pollCompose: [{
                type: Output
            }], cancel: [{
                type: Output
            }], formContent: [{
                type: ViewChild,
                args: ['formContent']
            }] } });
//# sourceMappingURL=data:application/json;base64, 