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 ]));
31 return window.location.protocol === 'https:';
34 customTrackBy(index: number, obj: any): any {
38 displayAddField(index: number) {
39 return index === (this.hosts.length - 1);
42 displayRemoveField(index: number) {
43 return (index !== 0 || this.hosts.length > 1) && index !== (this.hosts.length - 1);
47 // Do not check the last input
48 for (let i = 0; i < this.hosts.length - 1; i++) {
49 if (!this.form.controls[`host-${i}`].valid) return false;
52 const lastIndex = this.hosts.length - 1;
53 // If the last input (which is not the first) is empty, it's ok
54 if (this.hosts[lastIndex] === '' && lastIndex !== 0) {
57 return this.form.controls[`host-${lastIndex}`].valid;
61 removeField(index: number) {
62 // Remove the last control
63 this.form.removeControl(`host-${this.hosts.length - 1}`);
64 this.hosts.splice(index, 1);
70 const notEmptyHosts = this.getNotEmptyHosts();
71 if (notEmptyHosts.length === 0) {
72 this.error = 'You need to specify at least 1 host.';
76 if (!this.isHostsUnique(notEmptyHosts)) {
77 this.error = 'Hosts need to be unique.';
81 const confirmMessage = 'Are you sure to make friends with:\n - ' + notEmptyHosts.join('\n - ');
82 if (!confirm(confirmMessage)) return;
84 this.friendService.makeFriends(notEmptyHosts).subscribe(
86 // TODO: extractdatastatus
87 // if (status === 409) {
88 // alert('Already made friends!');
90 alert('Make friends request sent!');
91 this.router.navigate([ '/admin/friends/list' ]);
94 error => alert(error.text)
98 private getNotEmptyHosts() {
99 const notEmptyHosts = [];
101 Object.keys(this.form.value).forEach((hostKey) => {
102 const host = this.form.value[hostKey];
103 if (host !== '') notEmptyHosts.push(host);
106 return notEmptyHosts;
109 private isHostsUnique(hosts: string[]) {
110 return hosts.every(host => hosts.indexOf(host) === hosts.lastIndexOf(host));