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 { ConfirmService } from '../../../core';
8 import { validateHost } from '../../../shared';
9 import { FriendService } from '../shared';
12 selector: 'my-friend-add',
13 templateUrl: './friend-add.component.html',
14 styleUrls: [ './friend-add.component.scss' ]
16 export class FriendAddComponent implements OnInit {
22 private router: Router,
23 private notificationsService: NotificationsService,
24 private confirmService: ConfirmService,
25 private friendService: FriendService
29 this.form = new FormGroup({});
34 this.form.addControl(`host-${this.hosts.length}`, new FormControl('', [ validateHost ]));
39 return window.location.protocol === 'https:';
42 customTrackBy(index: number, obj: any): any {
46 displayAddField(index: number) {
47 return index === (this.hosts.length - 1);
50 displayRemoveField(index: number) {
51 return (index !== 0 || this.hosts.length > 1) && index !== (this.hosts.length - 1);
55 // Do not check the last input
56 for (let i = 0; i < this.hosts.length - 1; i++) {
57 if (!this.form.controls[`host-${i}`].valid) return false;
60 const lastIndex = this.hosts.length - 1;
61 // If the last input (which is not the first) is empty, it's ok
62 if (this.hosts[lastIndex] === '' && lastIndex !== 0) {
65 return this.form.controls[`host-${lastIndex}`].valid;
69 removeField(index: number) {
70 // Remove the last control
71 this.form.removeControl(`host-${this.hosts.length - 1}`);
72 this.hosts.splice(index, 1);
78 const notEmptyHosts = this.getNotEmptyHosts();
79 if (notEmptyHosts.length === 0) {
80 this.error = 'You need to specify at least 1 host.';
84 if (!this.isHostsUnique(notEmptyHosts)) {
85 this.error = 'Hosts need to be unique.';
89 const confirmMessage = 'Are you sure to make friends with:<br /> - ' + notEmptyHosts.join('<br /> - ');
90 this.confirmService.confirm(confirmMessage, 'Make friends').subscribe(
92 if (res === false) return;
94 this.friendService.makeFriends(notEmptyHosts).subscribe(
96 this.notificationsService.success('Sucess', 'Make friends request sent!');
97 this.router.navigate([ '/admin/friends/list' ]);
100 err => this.notificationsService.error('Error', err.text)
106 private getNotEmptyHosts() {
107 const notEmptyHosts = [];
109 Object.keys(this.form.value).forEach((hostKey) => {
110 const host = this.form.value[hostKey];
111 if (host !== '') notEmptyHosts.push(host);
114 return notEmptyHosts;
117 private isHostsUnique(hosts: string[]) {
118 return hosts.every(host => hosts.indexOf(host) === hosts.lastIndexOf(host));