import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MemberPermissions } from 'src/app/shared/crypto/group_config/chain-flag-parser';
import { NanoDialogBaseComponent } from 'src/app/shared/dialogs/nano-base-dialog';
import { AccountService } from 'src/app/shared/server-services/account.service';
import { AccountAvatarRecord } from 'src/app/shared/server-services/query-records/account-records';
import {
  DriveRoomRecord,
  DriveRecord,
} from 'src/app/shared/server-services/query-records/nano-records';
import { RoomService } from 'src/app/shared/server-services/room.service';

class RoomMemberRecord {
  avatar: AccountAvatarRecord;
  permissions: MemberPermissions;

  constructor(avatar, permissions) {
    (this.avatar = avatar), (this.permissions = permissions);
  }
}

@Component({
  selector: 'app-attach-room-dialog',
  templateUrl: './attach-room-dialog.component.html',
  styleUrls: ['./attach-room-dialog.component.scss'],
})
export class AttachRoomDialogComponent
  extends NanoDialogBaseComponent<AttachRoomDialogComponent>
  implements OnInit
{
  availableRooms: Array<DriveRoomRecord> = new Array<DriveRoomRecord>();
  selectedRoom: DriveRoomRecord;
  selectedRoomAllowAnonymous: boolean = false;
  displayedColumns: string[] = ['id', 'isActive', 'canWrite', 'canCreate'];
  /*selectedRoomMembers: MatTableDataSource<RoomMemberRecord> =
    new MatTableDataSource<RoomMemberRecord>();
  */
  selectedRoomMembers: RoomMemberRecord[];

  constructor(
    public dialogRef: MatDialogRef<AttachRoomDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public drive: DriveRecord,
    public roomService: RoomService,
    public accountService: AccountService
  ) {
    super(dialogRef);
  }

  ngOnInit(): void {
    this.roomService.getMyRooms().then((myRooms) => {
      if (myRooms.length == 0) {
        return;
      }

      myRooms.forEach((room) => {
        this.roomService.getRoom(room.id).then((room) => {
          if (!room.data.decryptionError) {
            var roomRecord: DriveRoomRecord = {
              id: room.id,
              name: room.data?.name,
              isValid: !this.hasActiveDriveSession(room.nanoSessions),
              avatar: room.data?.avatar,
            };
            console.log('room avatar', roomRecord);

            this.availableRooms.push(roomRecord);
          }
        });
      });
    });
  }

  setSelected(room: DriveRoomRecord): void {
    if (!room.isValid) {
      this.selectedRoom = room;
      return;
    }

    this.roomService.getMyRoomPermissions(room.id).then((res) => {
      this.selectedRoomAllowAnonymous = res.allowAnonymous;
    });
    this.roomService.getRoomConfig(room.id).then((res) => {
      let membershipMap = res.getMembersPermissions();
      let promises: Promise<any>[] = [];
      let roomMembers: RoomMemberRecord[] = [];

      membershipMap.forEach((value, key) => {
        promises.push(
          this.accountService.getAccount(key).then((user) => {
            roomMembers.push(new RoomMemberRecord(user, value));
          })
        );
      });

      Promise.all(promises).then(() => {
        this.accountService.getMe().then((me) => {
          for (let i = 0; i < roomMembers.length; i++) {
            if (roomMembers[i].avatar.id == me.id) {
              roomMembers[i].permissions.isAdmin = true;
              roomMembers[i].permissions.canWriteDrive = true;
              roomMembers[i].permissions.canUploadDrive = true;
              roomMembers[i].permissions.canAdhocDrive = true;
              break;
            }
          }
          //this.selectedRoomMembers.data = roomMembers;
          this.selectedRoomMembers = roomMembers.sort((m1, m2) => {
            if (m1.avatar.id == me.id) {
              return -1;
            } else if (m2.avatar.id == me.id) {
              return 1;
            }
            if (m1.permissions.isAdmin && !m2.permissions.isAdmin) {
              return -1;
            } else if (m2.permissions.isAdmin && !m1.permissions.isAdmin) {
              return 1;
            }

            if (m1.permissions.canWriteDrive && !m2.permissions.canWriteDrive) {
              return -1;
            } else if (m2.permissions.canWriteDrive && !m1.permissions.canWriteDrive) {
              return 1;
            }

            if (m1.permissions.canUploadDrive && !m2.permissions.canUploadDrive) {
              return -1;
            } else if (m2.permissions.canUploadDrive && !m1.permissions.canUploadDrive) {
              return 1;
            }

            return 0;
          });
          this.selectedRoom = room;
        });
      });
    });
  }

  attachRoom(room: DriveRoomRecord): void {
    this.dialogRef.close(room);
  }

  cancel() {
    this.dialogRef.close();
  }

  private hasActiveDriveSession(nanoSessions: Object): boolean {
    return Object.keys(nanoSessions).length > 0;
  }
}
