import { Component, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { Router } from '@angular/router';
import { of } from 'rxjs';
import { RefreshService } from '@shared/ui-api/refresh.service';

@Component({
  selector: 'app-invitation-overview',
  templateUrl: './invitation-overview.component.html',
  styleUrls: ['./invitation-overview.component.scss']
})
export class InvitationOverviewComponent extends DetailsComponentBase<any> implements OnInit {
  rolesStr: string;
  tokenMissingOrInvalid: boolean;

  constructor(
    public config: ConfigService,
    public notificationService: NotificationService,
    private router: Router,
    private refreshService: RefreshService,
  ) {
    super();
  }

  isLoggedIn(): boolean {
    return !!this.authSvc.userData?.user;
  }

  ngOnInit(refreshTimerInterval?: number) {
    if (this.isLoggedIn()) {
      this.authSvc.signalLoginCompleted();
      this.objectController.actionCallback = () => {
        this.authSvc.logout().subscribe(() => {
          this.refreshService.refresh();
        });
        return of(null);
      };
    }
    super.ngOnInit(refreshTimerInterval);
    if (this.object) {
      this.tokenMissingOrInvalid = this.object.token_missing || this.object.token_invalid;
      if (!this.tokenMissingOrInvalid) {
        if (this.object.roles) {
          this.rolesStr = this.object.roles.map(role => role.display_name).join(',');
        }
        if (this.object.invitation_automatically_accepted) {
          this.router.navigateByUrl(this.config.getPanelUrl('clients'));
        } else if (this.object.requires_sign_up === false) {
          this.router.navigateByUrl(
            this.config.getPanelUrl(`login/${this.object.invitation_id}/${this.object.used_token}`)
          );
        } else {
          this.router.navigateByUrl(
            this.config.getPanelUrl(`signup/${this.object.email}/${this.object.invitation_id}/${this.object.used_token}`)
          );
        }
      }
    }
  }
}
