import {
  Component,
  OnInit,
  OnDestroy,
  ViewChild,
  AfterViewInit
} from '@angular/core';
import { of, merge, Subscription } from 'rxjs';
import { Store } from '@ngrx/store';
import { map, catchError, startWith, switchMap } from 'rxjs/operators';

import { SessionStorageService } from '@ucap-webmessenger/web-storage';
import { DialogService } from '@ucap-webmessenger/ui';
import { LoginResponse } from '@ucap-webmessenger/protocol-authentication';
import { KEY_LOGIN_RES_INFO } from '@app/types/login-res-info.type';
import {
  MessageApiService,
  NoticeList,
  RetrieveNoticeRequest
} from '@ucap-webmessenger/api-message';
import { NGXLogger } from 'ngx-logger';
import { MatPaginator } from '@angular/material';
import {
  NoticeDetailDialogComponent,
  NoticeDetailDialogData
} from '../../dialogs/notice/notice-detail.dialog.component';

@Component({
  selector: 'app-layout-chat-right-drawer-notice',
  templateUrl: './notice.component.html',
  styleUrls: ['./notice.component.scss']
})
export class NoticeComponent implements OnInit, OnDestroy, AfterViewInit {
  loginRes: LoginResponse;

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  displayedColumns: string[] = ['title', 'regDate'];

  isLoadingResults = true;
  isRateLimitReached = false;
  defaultPageSize = 10; // default
  totalCount = 0;
  currentPage = 0;
  noticelist: NoticeList[] = [];
  noticeListSubscription: Subscription;

  constructor(
    private store: Store<any>,
    private sessionStorageService: SessionStorageService,
    private dialogService: DialogService,
    private messageApiService: MessageApiService,
    private logger: NGXLogger
  ) {
    this.loginRes = this.sessionStorageService.get<LoginResponse>(
      KEY_LOGIN_RES_INFO
    );
  }

  ngOnInit() {
    // this.getRetrieveNotice(this.currentPage);
  }

  ngOnDestroy(): void {
    if (!!this.noticeListSubscription) {
      this.noticeListSubscription.unsubscribe();
    }
  }

  ngAfterViewInit(): void {
    this.noticeListSubscription = merge(this.paginator.page)
      .pipe(
        startWith({}),
        switchMap(() => {
          this.isLoadingResults = true;
          return this.messageApiService.retrieveNotice({
            userSeq: this.loginRes.userSeq,
            companyCode: this.loginRes.companyCode,
            pageSize: this.defaultPageSize,
            pageCount: this.paginator.pageIndex
          } as RetrieveNoticeRequest);
        }),
        map(data => {
          // Flip flag to show that loading has finished.
          this.isLoadingResults = false;
          this.isRateLimitReached = false;

          this.totalCount = data.totalCount;
          this.currentPage = data.pageCount;
          this.noticelist = data.noticeList;

          return data.noticeList;
        }),
        catchError(() => {
          this.isLoadingResults = false;
          // Catch if the GitHub API has reached its rate limit. Return empty data.
          this.isRateLimitReached = true;
          return of([]);
        })
      )
      .subscribe(data => (this.noticelist = data));
  }

  onClickDetail(notice: NoticeList) {
    const result = this.dialogService.open<
      NoticeDetailDialogComponent,
      NoticeDetailDialogData
    >(NoticeDetailDialogComponent, {
      disableClose: false,
      width: '550px',
      data: {
        notice
      }
    });
  }
}
