import {Component, Input} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Title, Meta} from '@angular/platform-browser';

import {User, Session} from './utils/helper.class';
import {RouterHelper} from '../utils/routerHelper.class';

import {EnvProperties} from '../utils/properties/env-properties';
import {UserManagementService} from "../services/user-management.service";
import {properties} from "../../../environments/environment";
import {Subscriber} from "rxjs";
import {StringUtils} from "../utils/string-utils.class";

@Component({
  selector: 'user',
  templateUrl: 'user.component.html'
})

export class UserComponent {
  public user: User;
  public loading: boolean = true;
  public loggedIn: boolean = false;
  public server: boolean = true;
  public errorMessage: string = "";
  public password: string = "";
  private subscriptions = [];
  public errorCode: string = "";
  public redirectUrl: string = "";
  public routerHelper: RouterHelper = new RouterHelper();
  public properties: EnvProperties = properties;
  @Input() mainComponent = true;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private _meta: Meta,
              private _title: Title,
              private userManagementsService: UserManagementService) {
    this._title.setTitle("OpenAIRE | Login");
  }

  ngOnInit() {
    if (typeof document !== 'undefined') {
      this.server = false;
      this.userManagementsService.updateUserInfo( () => {
        this.user = this.userManagementsService.user;
        this.loggedIn = !!this.user;
        this.errorMessage = "";
        this.loading = true;
        this.subscriptions.push(this.route.queryParams.subscribe(params => {
          this.errorCode = params["errorCode"];
          this.redirectUrl = params["redirectUrl"];
          this.errorMessage = "";
          if (this.loggedIn && (this.errorCode == '1' || this.errorCode == '3'  || this.errorCode == '7')) {
            this.redirect();
          } else {
            this.loading = false;
          }
        }));
      });
    }
  }

  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }

  redirect(redirectUrl = null) {
    //if parameters are not read yet, force them to use the function parameter
    if(!this.redirectUrl && redirectUrl){
      this.redirectUrl = redirectUrl
    }
    if (this.redirectUrl && this.redirectUrl != "") {
      this.redirectUrl = decodeURIComponent(this.redirectUrl);
      this.userManagementsService.setRedirectUrl(this.redirectUrl);
      this.router.navigate(['/reload']);
    }
  }

  logIn() {
    this.userManagementsService.login();
  }
  
  getTheRolesFormatted(roles: string[]) {
    let formattedRoles = [];
    for (let role of roles) {
      if(role.indexOf("_MANAGER")!=-1){
        formattedRoles.push("Manager of " +  role.split("_")[1]);
      }else if((["FUNDER","COMMUNITY","INSTITUTION","PROJECT"]).indexOf(role.split("_")[0])!=-1){
        formattedRoles.push("Member of " +  role.split("_")[1]);
      }else{
        formattedRoles.splice(0,0,StringUtils.capitalize(role.split('_').join(' ').toLowerCase()));
      }
    }
    return formattedRoles.join(", ");
  }
  
  get isPortalAdministrator() {
    return Session.isPortalAdministrator(this.user);
  }


}
