import { Component, OnInit, Input, ViewChild, ElementRef, Output, EventEmitter } from '@angular/core'; import { SoldTournamentTicket, TicketGiftingPayload } from 'tournee.businesslogic'; import { FormGroup } from '@angular/forms'; import { Observable, fromEvent } from 'rxjs'; import { debounceTime, map } from 'rxjs/operators' import { AuthenticationService } from '../../services/authentication.service'; import { TournamentTicketsService } from '../../services/tournament.tickets.service'; @Component({ selector: 'app-mini-gifting-form', templateUrl: './mini-gifting-form.component.html', styleUrls: ['./mini-gifting-form.component.css'], providers: [ AuthenticationService, TournamentTicketsService ] }) export class MiniGiftingFormComponent implements OnInit { isWorking: boolean = false; @Output() OnError = new EventEmitter(); @Output() OnClearError = new EventEmitter(); @Output() OnCancel = new EventEmitter(); @Output() OnSuccess = new EventEmitter(); @ViewChild('nickname') nickname:ElementRef; @ViewChild('f') Form: FormGroup; @Input() ToGift: SoldTournamentTicket; validatingNickname: boolean = false; nicknameMatch: boolean = false; nicknameNoMatch: boolean = false; public input : Observable; gift_by: string = "email"; GiftPayload: TicketGiftingPayload = { sold_ticket_id: null, email: null, nickname: null } constructor(private _authentication: AuthenticationService, private _tickets: TournamentTicketsService) { } ngOnInit() { this.GiftPayload.sold_ticket_id = this.ToGift.sold_ticket_id; } ngAfterViewInit() { this.input = fromEvent(this.nickname.nativeElement, 'input') .pipe( debounceTime(300), map((e: KeyboardEvent) => e.target['value']) ); this.input.subscribe((val: string) => { this.nicknameChanged(val); }); } nicknameChanged($event: string) { this.validatingNickname = true; this.nicknameMatch = false; this.nicknameNoMatch = false; if ($event == '') { this.validatingNickname = false; return; } this._authentication.validateNickname($event) .then((result) => { this.validatingNickname = false; if (!result.result) { this.nicknameMatch = true; this.nicknameNoMatch = false; } else { this.Form.controls['nickname'].setErrors({ no_match: true }); this.nicknameMatch = false; this.nicknameNoMatch = true; } }) .catch((err) => { this.OnError.emit(err); }); } cancel() { this.OnCancel.emit(); } do_gifting() { if (this.isWorking) { return; } this.isWorking = true; this.OnClearError.emit(); this._tickets.gift_ticket(this.GiftPayload) .then(() => { this.isWorking = false; this.OnSuccess.emit(); }) .catch((err) => { this.isWorking = false; this.OnError.emit(err); }) } }