1 import { Component, OnInit } from '@angular/core';
2 import { FormControl, FormGroup } from '@angular/forms';
3 import { Router } from '@angular/router';
5 import { NotificationsService } from 'angular2-notifications';
7 import { validateHost } from '../../../shared';
8 import { FriendService } from '../shared';
11 selector: 'my-friend-add',
12 templateUrl: './friend-add.component.html',
13 styleUrls: [ './friend-add.component.scss' ]
15 export class FriendAddComponent implements OnInit {
21 private router: Router,
22 private notificationsService: NotificationsService,
23 private friendService: FriendService
27 this.form = new FormGroup({});
32 this.form.addControl(`host-${this.hosts.length}`, new FormControl('', [ validateHost ]));
37 return window.location.protocol === 'https:';
40 customTrackBy(index: number, obj: any): any {
44 displayAddField(index: number) {
45 return index === (this.hosts.length - 1);
48 displayRemoveField(index: number) {
49 return (index !== 0 || this.hosts.length > 1) && index !== (this.hosts.length - 1);
53 // Do not check the last input
54 for (let i = 0; i < this.hosts.length - 1; i++) {
55 if (!this.form.controls[`host-${i}`].valid) return false;
58 const lastIndex = this.hosts.length - 1;
59 // If the last input (which is not the first) is empty, it's ok
60 if (this.hosts[lastIndex] === '' && lastIndex !== 0) {
63 return this.form.controls[`host-${lastIndex}`].valid;
67 removeField(index: number) {
68 // Remove the last control
69 this.form.removeControl(`host-${this.hosts.length - 1}`);
70 this.hosts.splice(index, 1);
76 const notEmptyHosts = this.getNotEmptyHosts();
77 if (notEmptyHosts.length === 0) {
78 this.error = 'You need to specify at least 1 host.';
82 if (!this.isHostsUnique(notEmptyHosts)) {
83 this.error = 'Hosts need to be unique.';
87 const confirmMessage = 'Are you sure to make friends with:\n - ' + notEmptyHosts.join('\n - ');
88 if (!confirm(confirmMessage)) return;
90 this.friendService.makeFriends(notEmptyHosts).subscribe(
92 this.notificationsService.success('Sucess', 'Make friends request sent!');
93 this.router.navigate([ '/admin/friends/list' ]);
96 err => this.notificationsService.error('Error', err.text)
100 private getNotEmptyHosts() {
101 const notEmptyHosts = [];
103 Object.keys(this.form.value).forEach((hostKey) => {
104 const host = this.form.value[hostKey];
105 if (host !== '') notEmptyHosts.push(host);
108 return notEmptyHosts;
111 private isHostsUnique(hosts: string[]) {
112 return hosts.every(host => hosts.indexOf(host) === hosts.lastIndexOf(host));