import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
import { TranslateService } from '@ngx-translate/core';
import { AccountService } from 'src/app/shared/server-services/account.service';
import { DialogueService } from 'src/app/shared/server-services/dialogue.service';
import { AccountAvatarRecord } from 'src/app/shared/server-services/query-records/account-records';
import { DialogueRecord } from 'src/app/shared/server-services/query-records/room-records';
import { SidebarResource } from 'src/app/shared/server-services/query-records/sidebar-records';
import { WorkspaceSubscriptionDialogueEventRecord } from 'src/app/shared/server-services/query-records/workspace-records';
import {
  SubscriptionServiceEvent,
  SubscriptionServiceEventType,
} from 'src/app/shared/server-services/subscription-event';
import { SubscriptionService } from 'src/app/shared/server-services/subscription.service';
import { RouterHandler } from 'src/app/shared/services/router-handler.service';
import { sideMenuActiveObserver } from 'src/app/shared/shared-observers';

@Component({
  selector: 'app-sidebar-dialogue',
  templateUrl: './sidebar-dialogue.component.html',
  styleUrls: ['./sidebar-dialogue.component.scss'],
})
export class SidebarDialogueComponent implements OnInit, OnDestroy {
  @Input() sidebarResourceData: SidebarResource;
  public avatar: AccountAvatarRecord;
  public dialogeRecord: DialogueRecord;

  public name: string;
  public news: boolean;
  public error: boolean = false;

  public selectedMenu = false;

  private onRouterChange = (res) => {
    this.selectedMenu = this.sidebarResourceData.id == res?.params?.id;
  };

  constructor(
    private routerHandler: RouterHandler,
    private subscriptionService: SubscriptionService,
    private accountService: AccountService,
    private dialogueService: DialogueService,
    private translateService: TranslateService
  ) {
    this.routerHandler.subscribeAll(this.onRouterChange);

    this.subscriptionService.subscribe(
      SubscriptionServiceEvent.DIALOGUE_EVENT,
      SubscriptionServiceEventType.MODIFY,
      this.updateData
    );
  }

  ngOnInit(): void {
    this.dialogueService.getData(this.sidebarResourceData.id).then((dialogue) => {
      this.dialogeRecord = dialogue;
      this.refreshState();
    });
  }

  private updateData = (event: WorkspaceSubscriptionDialogueEventRecord) => {
    if (this.sidebarResourceData.id == event.id) {
      this.refreshState();
    }
  };

  public visibilityChange(visible: boolean) {
    if (!this.avatar && visible) {
      this.loadUserData();
    }
  }

  private loadUserData() {
    this.accountService
      .getAccount(this.sidebarResourceData.id)
      .then((account) => {
        this.avatar = account;

        if (account.deleted) {
          this.error = true;
          this.name = this.translateService.instant(marker('Deleted user'));
        } else {
          this.name = account.avatarName;
        }
      })
      .catch((e) => {
        console.error('could not load the user', e);
        this.name = marker('Error');
        this.error = true;
      });
  }

  /**
   * Refresh all the view-based variables to trigger changes
   */
  private refreshState() {
    this.news =
      (this.dialogeRecord.seenMessageId == null && this.dialogeRecord.topMessageId !== null) ||
      this.dialogeRecord.seenMessageId < this.dialogeRecord.topMessageId;
  }

  ngOnDestroy(): void {
    this.routerHandler.unsubscribeAll(this.onRouterChange);
    this.subscriptionService.unsubscribe(
      SubscriptionServiceEvent.DIALOGUE_EVENT,
      SubscriptionServiceEventType.MODIFY,
      this.updateData
    );
  }

  hideSidebar(): void {
    sideMenuActiveObserver.next(false);
  }
}
