1 import { Component, OnInit } from '@angular/core';
2 import { FormControl, FormGroup, REACTIVE_FORM_DIRECTIVES } from '@angular/forms';
3 import { Router } from '@angular/router';
5 import { validateUrl } from '../../../shared';
6 import { FriendService } from '../shared';
9 selector: 'my-friend-add',
10 template: require('./friend-add.component.html'),
11 styles: [ require('./friend-add.component.scss') ],
12 directives: [ REACTIVE_FORM_DIRECTIVES ]
14 export class FriendAddComponent implements OnInit {
15 friendAddForm: FormGroup;
19 constructor(private router: Router, private friendService: FriendService) {}
22 this.friendAddForm = new FormGroup({});
27 this.friendAddForm.addControl(`url-${this.urls.length}`, new FormControl('', [ validateUrl ]));
31 customTrackBy(index: number, obj: any): any {
35 displayAddField(index: number) {
36 return index === (this.urls.length - 1);
39 displayRemoveField(index: number) {
40 return (index !== 0 || this.urls.length > 1) && index !== (this.urls.length - 1);
44 // Do not check the last input
45 for (let i = 0; i < this.urls.length - 1; i++) {
46 if (!this.friendAddForm.controls[`url-${i}`].valid) return false;
49 const lastIndex = this.urls.length - 1;
50 // If the last input (which is not the first) is empty, it's ok
51 if (this.urls[lastIndex] === '' && lastIndex !== 0) {
54 return this.friendAddForm.controls[`url-${lastIndex}`].valid;
58 removeField(index: number) {
59 // Remove the last control
60 this.friendAddForm.removeControl(`url-${this.urls.length - 1}`);
61 this.urls.splice(index, 1);
67 const notEmptyUrls = this.getNotEmptyUrls();
68 if (notEmptyUrls.length === 0) {
69 this.error = 'You need to specify at less 1 url.';
73 if (!this.isUrlsUnique(notEmptyUrls)) {
74 this.error = 'Urls need to be unique.';
78 const confirmMessage = 'Are you sure to make friends with:\n - ' + notEmptyUrls.join('\n - ');
79 if (!confirm(confirmMessage)) return;
81 this.friendService.makeFriends(notEmptyUrls).subscribe(
84 alert('Already made friends!');
86 alert('Make friends request sent!');
87 this.router.navigate([ '/admin/friends/list' ]);
94 private getNotEmptyUrls() {
95 const notEmptyUrls = [];
97 this.urls.forEach((url) => {
98 if (url !== '') notEmptyUrls.push(url);
104 private isUrlsUnique(urls: string[]) {
105 return urls.every(url => urls.indexOf(url) === urls.lastIndexOf(url));