import { ChangeDetectorRef, Component, Inject, Input, OnInit, AfterViewInit } from '@angular/core'; import { Poll } from '../../../core/models/poll.model'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ApiService } from '../../../core/services/api.service'; import { ToastService } from '../../../core/services/toast.service'; import { PollService } from '../../../core/services/poll.service'; import { DOCUMENT } from '@angular/common'; import { Router } from '@angular/router'; import { environment } from '../../../../environments/environment'; import { PollUtilitiesService } from '../../../core/services/poll.utilities.service'; import { StorageService } from '../../../core/services/storage.service'; import { DateUtilitiesService } from '../../../core/services/date.utilities.service'; @Component({ selector: 'app-admin-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss'], }) export class FormComponent implements OnInit, AfterViewInit { @Input() public poll?: Poll; public form: FormGroup; public displayDatePicker = false; public advancedDisplayEnabled = false; public show_debug_data = false; public currentStep = 'base'; public steps = ['base', 'choices', 'advanced']; public environment = environment; constructor( private fb: FormBuilder, private cd: ChangeDetectorRef, private pollUtilitiesService: PollUtilitiesService, private toastService: ToastService, private pollService: PollService, private storageService: StorageService, public apiService: ApiService, public dateUtils: DateUtilitiesService, private router: Router, private utilitiesService: PollUtilitiesService, @Inject(DOCUMENT) private document: any ) {} ngOnInit(): void { this.initFormDefault(); // this.goNextStep(); } ngAfterViewInit() { // focus on first field of the creation form const firstField = this.document.querySelector('#kind'); if (firstField) { console.log('focus on ', firstField); firstField.focus(); } else { console.log('no first field of form'); } } initFormDefault(showDemoValues = environment.autofill): void { const creationDate = new Date(); // choices of date are managed outside of this form this.form = this.fb.group({ title: ['', [Validators.required, Validators.minLength(5)]], creatorPseudo: ['', [Validators.required]], creatorEmail: ['', [Validators.required, Validators.email]], custom_url: [this.pollUtilitiesService.makeUuid(), [Validators.required]], description: ['', [Validators.required]], kind: ['date', [Validators.required]], areResultsPublic: [true, [Validators.required]], whoCanChangeAnswers: ['everybody', [Validators.required]], isProtectedByPassword: [false, [Validators.required]], allowNewDateTime: [false, [Validators.required]], isOwnerNotifiedByEmailOnNewVote: [false, [Validators.required]], isOwnerNotifiedByEmailOnNewComment: [false, [Validators.required]], isYesAnswerAvailable: [false, [Validators.required]], isMaybeAnswerAvailable: [false, [Validators.required]], isNoAnswerAvailable: [false, [Validators.required]], isAboutDate: [true, [Validators.required]], isZeroKnoledge: [false, [Validators.required]], useVoterUniqueLink: [false, [Validators.required]], expiresDaysDelay: [60, [Validators.required, Validators.min(1), Validators.max(365)]], maxCountOfAnswers: [150, [Validators.required, Validators.min(1), Validators.max(5000)]], allowComments: [true, [Validators.required]], password: ['', []], voterEmailList: ['', []], dateCreated: [creationDate, [Validators.required]], hasSeveralHours: [false, [Validators.required]], hasMaxCountOfAnswers: [true, [Validators.required, Validators.min(1)]], startDateInterval: ['', [Validators.required]], endDateInterval: ['', [Validators.required]], }); // take back values from pollservice // this.form.patchValue(this.pollService.poll); this.setDefaultFormValues(); if (showDemoValues) { this.setDemoValues(); this.toastService.display('default values filled for demo'); } if (environment.autoSendNewPoll) { this.createPoll(); } } setDefaultFormValues(): void { const dateStart = this.dateUtils.formateDateToInputStringNg(new Date()); const dateEnd = this.dateUtils.formateDateToInputStringNg(this.dateUtils.addDaysToDate(5, new Date())); this.form.patchValue({ creatorPseudo: 'Anne Onyme', creatorEmail: '', description: 'RSVP', isAboutDate: true, hasSeveralHours: false, kind: 'date', password: '', whoCanChangeAnswers: 'everybody', isProtectedByPassword: false, isOwnerNotifiedByEmailOnNewVote: false, isOwnerNotifiedByEmailOnNewComment: false, isYesAnswerAvailable: true, isMaybeAnswerAvailable: false, isNoAnswerAvailable: false, isZeroKnoledge: true, areResultsPublic: true, allowComments: true, expiresDaysDelay: 60, maxCountOfAnswers: 150, allowNewDateTime: false, startDateInterval: dateStart, endDateInterval: dateEnd, }); this.automaticSlug(); } /** * add example values to the form, overrides defaults of PollConfiguration */ setDemoValues(): void { const title = 'le titre de démo __ ' + new Date().getTime(); this.form.patchValue({ creatorPseudo: 'Chuck Norris', creatorEmail: 'chucknorris@example.com' }); const dateStart = this.dateUtils.formateDateToInputStringNg(new Date()); const dateEnd = this.dateUtils.formateDateToInputStringNg(this.dateUtils.addDaysToDate(5, new Date())); this.form.patchValue({ title: title, custom_url: this.pollUtilitiesService.makeSlugFromString(title), description: 'répondez SVP <3 ! *-*', creatorPseudo: 'Chuck Norris', creatorEmail: 'chucknorris@example.com', dateStart, dateEnd, }); } askInitFormDefault(): void { this.toastService.display('formulaire réinitialisé', 'info'); } /** * set the poll custom_url from other data of the poll */ automaticSlug(): void { this.form.patchValue({ custom_url: this.pollService.convertTextToSlug(this.form.value.title) + '_' + this.utilitiesService.makeUuid().substr(0, 12), }); } goPreviousStep() { alert('todo'); } goNextStep() { let indexCurrentStep = this.steps.indexOf(this.currentStep); indexCurrentStep += 1; this.currentStep = this.steps[indexCurrentStep]; window.scrollTo(0, 0); } public createPoll(): void { const newpoll = this.pollService.newPollFromForm(this.form); console.log('newpoll', newpoll); const router = this.router; if (!environment.production) { this.toastService.display('mode dev : envoi du form sans validation'); this.apiService.createPoll(newpoll).then( (resp: any) => { this.pollService.updateCurrentPoll(resp.data.poll); this.storageService.userPolls.push(resp.data.poll); this.storageService.vote_stack.owner.polls.push(resp.data.poll); this.toastService.display('sauvegarde du nouveau sondage réussie'); router.navigate(['success']); }, (err) => { this.toastService.display('erreur lors de la sauvegarde ' + err.message); } ); } else { if (this.form.valid) { this.toastService.display("C'est parti!"); this.apiService.createPoll(newpoll).then( (resp: any) => { this.pollService.updateCurrentPoll(resp.data.poll); this.storageService.userPolls.push(resp.data.poll); this.storageService.vote_stack.owner.polls.push(resp.data.poll); this.toastService.display('sauvegarde du nouveau sondage réussie'); router.navigate(['success']); }, (err) => { this.toastService.display('erreur lors de la sauvegarde'); } ); } else { this.toastService.display('invalid form'); } } } }