import { Component, OnInit, OnDestroy } from '@angular/core';
import { NGXLogger } from 'ngx-logger';
import { ucapAnimations } from '@ucap-webmessenger/ui';
import { Observable } from 'rxjs';
import { Store, select } from '@ngrx/store';

import * as AppStore from '@app/store';
import * as MessageStore from '@app/store/messenger/message';
import * as SettingsStore from '@app/store/messenger/settings';
import { MatTabChangeEvent } from '@angular/material';
import { MainMenu } from '@app/types';

@Component({
  selector: 'app-layout-messenger-left-nav',
  templateUrl: './left-nav.component.html',
  styleUrls: ['./left-nav.component.scss'],
  animations: ucapAnimations
})
export class LeftNaviComponent implements OnInit, OnDestroy {
  badgeChatUnReadCount$: Observable<number>;
  badgeMessageUnReadCount$: Observable<number>;
  badgeMessageInterval: any;

  MainMenu = MainMenu;

  constructor(private store: Store<any>, private logger: NGXLogger) {}

  ngOnInit() {
    /** About Chat Badge */
    this.badgeChatUnReadCount$ = this.store.pipe(
      select(AppStore.MessengerSelector.SyncSelector.selectChatUnreadCount)
    );

    /** About Message Badge */
    this.badgeMessageUnReadCount$ = this.store.pipe(
      select(AppStore.MessengerSelector.MessageSelector.unReadMessageCount)
    );

    this.getMessageUnreadCount();
    this.badgeMessageInterval = setInterval(
      () => this.getMessageUnreadCount(),
      5 * 60 * 1000
    );
  }

  ngOnDestroy(): void {
    if (!!this.badgeMessageInterval) {
      clearInterval(this.badgeMessageInterval);
    }

    this.logger.debug('-----------------------LeftNaviComponent ngOnDestroy');
  }

  onSelectedTabChange(event: MatTabChangeEvent) {
    this.store.dispatch(
      SettingsStore.selectedGnbMenuIndex({
        menuIndex: event.tab.ariaLabel as MainMenu
      })
    );
  }

  getMessageUnreadCount(): void {
    this.store.dispatch(MessageStore.retrieveUnreadCount({}));
  }
}
