import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
import { ObjectSorter } from '../../object-sorter';
import { SafeRadix32 } from '../../safe-radix32';
import { AccountService } from '../../server-services/account.service';
import { AccountAvatarRecord } from '../../server-services/query-records/account-records';
import { SubscriptionService } from '../../server-services/subscription.service';
import { DialogService } from '../../services/dialog.service';
import { WeightedSearch } from '../../weighted-search';
import { NanoDialogBaseComponent } from '../nano-base-dialog';

export interface inviteListUser {
  user: AccountAvatarRecord;
  isMember: boolean;
  isMarked: boolean;
}

export type InviteUserDialogData = {
  member: AccountAvatarRecord[];
  currentMember?: number;
  maxMember?: number;
};

@Component({
  selector: 'app-invite-user-dialog',
  templateUrl: './invite-user-dialog.component.html',
  styleUrls: ['./invite-user-dialog.component.scss'],
})
export class InviteUserDialogComponent extends NanoDialogBaseComponent<InviteUserDialogComponent> {
  public allUsersFromWorkspace: inviteListUser[] = [];
  public showList: inviteListUser[] = [];
  private membersIds: string[] = [];
  public loadingState: boolean = false;
  public currentMember: number;
  public maxMember: number;
  public markedUser: number = 0;

  constructor(
    public dialogRef: MatDialogRef<InviteUserDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: InviteUserDialogData,
    private accountService: AccountService,
    private subscriptionService: SubscriptionService,
    private dialogService: DialogService
  ) {
    super(dialogRef);
    this.currentMember = data.currentMember;
    this.maxMember = data.maxMember;

    this.data.member.forEach((user) => {
      this.membersIds.push(user.id);
    });

    this.subscriptionService.subscribeWorkspaceLoaded(() => {
      this.accountService.getAllAccount().then((res: AccountAvatarRecord[]) => {
        res.forEach((user) => {
          this.allUsersFromWorkspace.push({
            user,
            isMember: this.membersIds.indexOf(user.id) > -1,
            isMarked: false,
          });
        });

        this.showList = [];

        this.allUsersFromWorkspace.forEach((user) => {
          this.showList.push(user);
        });

        ObjectSorter.sort(this.showList, 'user.avatarName');
      });
    });
  }

  public save() {
    if (!this.maxMember || this.currentMember + this.markedUser <= this.maxMember) {
      let result = [];
      this.allUsersFromWorkspace.forEach((u) => {
        if (u.isMarked) {
          result.push(u.user);
        }
      });

      this.dialogRef.close(result);
    } else {
      this.dialogService.openAlertDialog(marker('Error'), marker('Member limit reached'));
    }
  }

  public search(s) {
    if (SafeRadix32.isSafeRadix(s)) {
      this.searchById(s);
    } else {
      this.showList = WeightedSearch.search(s, ['user.avatarName'], this.allUsersFromWorkspace);
    }
  }

  private searchById(id: string): void {
    this.accountService
      .getAccount(id)
      .then((res) => {
        let newMember = {
          user: res,
          isMember: this.membersIds.indexOf(res.id) > -1,
          isMarked: false,
        };

        this.showList = [newMember];
        this.allUsersFromWorkspace.push(newMember);
      })
      .catch((err) => {});
  }

  public markUser(m: inviteListUser) {
    if (m.isMember) return;

    if (m.isMarked) {
      this.markedUser--;
    } else {
      this.markedUser++;
    }
    m.isMarked = !m.isMarked;
  }
}
