import {Component, Input, OnInit} from "@angular/core";
import {StakeholderService} from "../openaireLibrary/monitor/services/stakeholder.service";
import {properties} from "../../environments/environment";
import {Subscriber} from "rxjs";
import {Title} from "@angular/platform-browser";
import {Composer} from "../openaireLibrary/utils/email/composer";
import {Email} from "../openaireLibrary/utils/email/email";
import {ActivatedRoute} from "@angular/router";

type Tab = 'member' | 'manager';

@Component({
  selector: 'users',
  templateUrl: 'users.component.html'
})
export class UsersComponent implements OnInit {
  
  public alias: string;
  public name: string;
  public type: string;
  public link: string;
  public loading: boolean;
  public messages: Map<Tab, string> = new Map<Tab, string>();
  public tab: Tab = 'manager';
  private subscriptions = [];
  public emailComposer: Function = (name, recipient, role): Email => {
    return Composer.composeEmailForMonitorDashboard(name, recipient, role);
  }
  
  constructor(private stakeholderService: StakeholderService,
              private route: ActivatedRoute,
              private title: Title) {
  }
  
  ngOnInit() {
    this.loading = true;
    this.subscriptions.push(this.route.fragment.subscribe((fragment: Tab) => {
      if (this.isTab(fragment)) {
        this.tab = fragment;
      } else {
        this.tab = 'manager';
      }
    }));
    this.subscriptions.push(this.stakeholderService.getStakeholderAsObservable().subscribe(stakeholder => {
      if (stakeholder) {
        this.alias = stakeholder.alias;
        this.name = stakeholder.name;
        this.title.setTitle(this.name + " | Users");
        this.type = stakeholder.type;
        this.link = this.getURL(this.alias);
        this.messages.set("member", 'A member has the right to view the <b>restricted access</b> areas of this indicator\'s profile. ' +
          'A member has <b>no access</b> to the administration part of the profile.');
        this.messages.set("manager", 'A manager has the right to access the administration part of this indicator\'s profile, ' +
          'where he is able to customize and manage indicators, and invite other users as members.');
        this.loading = false;
      }
    }));
  }
  
  ngOnDestroy() {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      }
    });
  }
  
  private isTab(tab: Tab): boolean {
   switch (tab) {
     case "manager":
       return true;
     case "member":
       return true;
     default:
       return false;
   }
  }
  
  private getURL(id: string): string {
    return properties.domain + properties.baseLink + "/" + id + "?verify=";
  }
}
