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 this.urls.splice(index, 1);
65 const notEmptyUrls = this.getNotEmptyUrls();
66 if (notEmptyUrls.length === 0) {
67 this.error = 'You need to specify at less 1 url.';
71 if (!this.isUrlsUnique(notEmptyUrls)) {
72 this.error = 'Urls need to be unique.';
76 const confirmMessage = 'Are you sure to make friends with:\n - ' + notEmptyUrls.join('\n - ');
77 if (!confirm(confirmMessage)) return;
79 this.friendService.makeFriends(notEmptyUrls).subscribe(
82 alert('Already made friends!');
84 alert('Make friends request sent!');
85 this.router.navigate([ '/admin/friends/list' ]);
92 private getNotEmptyUrls() {
93 const notEmptyUrls = [];
95 this.urls.forEach((url) => {
96 if (url !== '') notEmptyUrls.push(url);
102 private isUrlsUnique(urls: string[]) {
103 return urls.every(url => urls.indexOf(url) === urls.lastIndexOf(url));