import {Component} from "@angular/core";
import {Router} from "@angular/router";
import {WebbpmTokenProvider} from "../provider/webbpm-token-provider";

@Component({
             moduleId: module.id,
             selector: 'token-form',
             templateUrl: './../../../../../src/resources/template/webbpm/jwt-form.html'
           })
export class TokenFormComponent {

  name: string = '';
  realm: string = '';
  recruitmentId: string = '';
  role: string = '';

  private readonly encodedHeader = this.encodeBase64Url(JSON.stringify({
                                                         kid: "69d4a060-4053-4056-ae69-5e9bcf41125f",
                                                         typ: "JWT",
                                                         alg: "RS512"
                                                       }));

  constructor(private router: Router) {
  }

  public enter() {
    localStorage.setItem(WebbpmTokenProvider.ACCESS_TOKEN_STORAGE_KEY, this.generateToken());
    this.router.navigateByUrl('');
  }

  private generateToken(): string {
    let claims = {
      name: this.name,
      realm: this.realm,
      recruitmentId: this.recruitmentId,
      roles: [this.role]
    };
    return `${this.encodedHeader}.${this.encodeBase64Url(JSON.stringify(claims))}.`
  }

  private encodeBase64Url(input: string): string {
    let bytes = new TextEncoder().encode(input);
    const byteArray = Array.from(bytes);
    const binString = String.fromCharCode(...byteArray);
    return btoa(binString).replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '');
  }
}