import {Component, Input} from '@angular/core';
import {Title, Meta} from '@angular/platform-browser';
import {User} from "../../login/utils/helper.class";
import {UserManagementService} from "../../services/user-management.service";
import {LoginErrorCodes} from "../../login/utils/guardHelper.class";
import {Router} from "@angular/router";
import {Subscriber} from "rxjs";


@Component({
  selector: 'claims-admin',
  template: `
    <div [class.uk-section]="!isConnect">
      <div uk-grid class="uk-margin-small-top">
        <div class="tm-main uk-width-1-1@s uk-width-1-1@m  uk-width-1-1@l uk-row-first">
          <div [class.uk-container]="!isConnect" [class.uk-container-large]="!isConnect">
            <h1 *ngIf="!isConnect" class="uk-h2">
              Manage links
            </h1>
            <div>
              <displayClaims *ngIf="user" [user]="user" [enableDelete]=true [myClaims]=false
                             [isAdmin]=true [fetchBy]="(fetchId=='openaire')?null:fetchBy"
                             [fetchId]="(fetchId=='openaire')?null:fetchId" [actions]="isConnect"
                             [communityId]="(fetchBy && fetchBy == 'Context' && fetchId && fetchId!='openaire')?fetchId:null"
                             [externalPortalUrl]=externalPortalUrl [claimsInfoURL]=claimsInfoURL
                             pageTitle="Manage links"></displayClaims>
            </div>
          </div>
        </div>
      </div>
    </div>
  `,
})
export class ClaimsAdminComponent {
  @Input() fetchBy: string;
  @Input() fetchId: string;
  @Input() isConnect: boolean = false;
  @Input() externalPortalUrl: string;
  @Input() claimsInfoURL: string;
  public user: User = null;
  sub;
  
  constructor(private _meta: Meta, private _title: Title,
              private userManagementService: UserManagementService, private _router: Router) {
    if (!this.isConnect) {
      this._title.setTitle("OpenAIRE | Manage links ");
    }
  }
  
  ngOnDestroy() {
    if (this.sub instanceof Subscriber) {
      this.sub.unsubscribe();
    }
  }
  
  ngOnInit() {
    this.sub = this.userManagementService.getUserInfo().subscribe(user => {
      this.user = user;
      if (!user) {
        this._router.navigate(['/user-info'], {
          queryParams: {
            "errorCode": LoginErrorCodes.NOT_VALID,
            "redirectUrl": this._router.url
          }
        });
      }
    });
  }
}
