import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
import { base64 } from 'rfc4648';
import { AuthService } from '../../server-services/auth.service';
import { RoomService } from '../../server-services/room.service';
import { ClipboardService } from '../../services/clipboard.service';
import { DialogService } from '../../services/dialog.service';
import { SnackBarService } from '../../services/snackbar.service';
import msgpack from 'msgpack-lite';

@Component({
  selector: 'app-room-configuration-dialog',
  templateUrl: './room-configuration-dialog.component.html',
  styleUrls: ['./room-configuration-dialog.component.scss'],
})
export class RoomConfigurationDialogComponent implements OnInit {
  constructor(
    @Inject(MAT_DIALOG_DATA) public resourceId: string,
    private clipboardService: ClipboardService,
    private snackbarService: SnackBarService,
    private dialogService: DialogService,
    private roomService: RoomService,
    private authService: AuthService
  ) {
    this.roomService
      .getRoomBlockChain(this.resourceId, this.authService.getSelfAccountKeyring())
      .then((chain) => {
        // create connector string
        let encodedBlockChainHead = base64.stringify(
          msgpack.encode({
            id: this.resourceId,
            block_names: chain.head_names,
          })
        );

        this.encodedBlockChainHead = encodedBlockChainHead;
      });
  }

  public encodedBlockChainHead = '';

  ngOnInit(): void {}

  public copyBlockChainHead() {
    if (this.encodedBlockChainHead) {
      // copy to the clipboard
      this.clipboardService
        .copy(this.encodedBlockChainHead)
        .then(() => {
          this.snackbarService.showSnackbar(marker('Url copied to clipboard'));
        })
        .catch((err) => {
          console.error('clipboard err', err);
          this.dialogService.openAlertDialog(
            marker('Copy Error'),
            marker('Could not copy to the clipboard')
          );
        });
    }
  }
}
