1 import { Component, OnInit } from '@angular/core';
2 import { FormControl, FormGroup } from '@angular/forms';
3 import { Router } from '@angular/router';
5 import { validateHost } from '../../../shared';
6 import { FriendService } from '../shared';
9 selector: 'my-friend-add',
10 templateUrl: './friend-add.component.html',
11 styleUrls: [ './friend-add.component.scss' ]
13 export class FriendAddComponent implements OnInit {
18 constructor(private router: Router, private friendService: FriendService) {}
21 this.form = new FormGroup({});
26 this.form.addControl(`host-${this.hosts.length}`, new FormControl('', [ validateHost ]));
30 customTrackBy(index: number, obj: any): any {
34 displayAddField(index: number) {
35 return index === (this.hosts.length - 1);
38 displayRemoveField(index: number) {
39 return (index !== 0 || this.hosts.length > 1) && index !== (this.hosts.length - 1);
43 // Do not check the last input
44 for (let i = 0; i < this.hosts.length - 1; i++) {
45 if (!this.form.controls[`host-${i}`].valid) return false;
48 const lastIndex = this.hosts.length - 1;
49 // If the last input (which is not the first) is empty, it's ok
50 if (this.hosts[lastIndex] === '' && lastIndex !== 0) {
53 return this.form.controls[`host-${lastIndex}`].valid;
57 removeField(index: number) {
58 // Remove the last control
59 this.form.removeControl(`host-${this.hosts.length - 1}`);
60 this.hosts.splice(index, 1);
66 const notEmptyHosts = this.getNotEmptyHosts();
67 if (notEmptyHosts.length === 0) {
68 this.error = 'You need to specify at least 1 host.';
72 if (!this.isHostsUnique(notEmptyHosts)) {
73 this.error = 'Hosts need to be unique.';
77 const confirmMessage = 'Are you sure to make friends with:\n - ' + notEmptyHosts.join('\n - ');
78 if (!confirm(confirmMessage)) return;
80 this.friendService.makeFriends(notEmptyHosts).subscribe(
82 // TODO: extractdatastatus
83 // if (status === 409) {
84 // alert('Already made friends!');
86 alert('Make friends request sent!');
87 this.router.navigate([ '/admin/friends/list' ]);
90 error => alert(error.text)
94 private getNotEmptyHosts() {
95 const notEmptyHosts = [];
97 Object.keys(this.form.value).forEach((hostKey) => {
98 const host = this.form.value[hostKey];
99 if (host !== '') notEmptyHosts.push(host);
102 return notEmptyHosts;
105 private isHostsUnique(hosts: string[]) {
106 return hosts.every(host => hosts.indexOf(host) === hosts.lastIndexOf(host));