import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { MatPaginator, MatTableDataSource, MatSort } from '@angular/material';
import {
  FileInfo,
  FileDownloadInfo,
  FileType
} from '@ucap-webmessenger/protocol-file';
import { Subscription, combineLatest } from 'rxjs';
import { Store, select } from '@ngrx/store';

import * as AppStore from '@app/store';
import * as ChatStore from '@app/store/messenger/chat';
import { tap, map } from 'rxjs/operators';
import { FileUtil } from '@ucap-webmessenger/core';
import { LoginResponse } from '@ucap-webmessenger/protocol-authentication';
import { SessionStorageService } from '@ucap-webmessenger/web-storage';
import { KEY_LOGIN_RES_INFO } from '@app/types/login-res-info.type';

export interface FileInfoTotal {
  info: FileInfo;
  checkInfo: FileDownloadInfo[];
}

@Component({
  selector: 'app-layout-chat-right-drawer-file-box',
  templateUrl: './file-box.component.html',
  styleUrls: ['./file-box.component.scss']
})
export class FileBoxComponent implements OnInit, OnDestroy {
  displayedColumns: string[] = ['check', 'name', 'sendDate'];
  dataSource = new MatTableDataSource<FileInfoTotal>();

  fileInfoTotal: FileInfoTotal[];
  fileInfoList: FileInfo[];
  fileInfoListSubscription: Subscription;

  selectedFile: FileInfoTotal;
  selectedFileList: FileInfoTotal[] = [];

  loginRes: LoginResponse;

  currentTabIndex = 0;

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: true }) sort: MatSort;

  constructor(
    private store: Store<any>,
    private sessionStorageService: SessionStorageService
  ) {
    this.loginRes = this.sessionStorageService.get<LoginResponse>(
      KEY_LOGIN_RES_INFO
    );
  }

  ngOnInit() {
    this.fileInfoListSubscription = combineLatest([
      this.store.pipe(select(AppStore.MessengerSelector.RoomSelector.roomInfo)),
      this.store.pipe(
        select(AppStore.MessengerSelector.EventSelector.selectAllFileInfoList)
      ),
      this.store.pipe(
        select(
          AppStore.MessengerSelector.EventSelector.selectAllFileInfoCheckList
        )
      )
    ])
      .pipe(
        tap(() => (this.fileInfoTotal = [])),
        tap(([roomInfo, fileInfoList, fileInfoCheckList]) => {
          this.fileInfoList = fileInfoList.filter(fileInfo => {
            if (
              fileInfo.roomSeq === roomInfo.roomSeq &&
              (fileInfo.type === FileType.File ||
                fileInfo.type === FileType.Sound)
            ) {
              return true;
            } else {
              return false;
            }
          });

          this.fileInfoList.map(fileInfo => {
            this.fileInfoTotal.push({
              info: fileInfo,
              checkInfo: fileInfoCheckList.filter(
                checkInfo => checkInfo.seq === fileInfo.seq
              )
            });
          });

          this.onSelectedIndexChange(this.currentTabIndex);
        })
      )
      .subscribe();

    this.dataSource.sortingDataAccessor = (item, property) => {
      switch (property) {
        case 'name':
          return item.info.name;
        case 'size':
          return item.info.size;
        case 'sendDate':
          return item.info.sendDate;
        default:
          return item.info[property];
      }
    };
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
  }

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

  getExtention(name: string): string {
    return FileUtil.getExtension(name);
  }

  onSelectedIndexChange(index: number) {
    this.selectedFile = null;
    this.currentTabIndex = index;
    if (this.currentTabIndex === 0) {
      // Receive
      this.dataSource.data = this.fileInfoTotal.filter(
        fileInfo => fileInfo.info.senderSeq !== this.loginRes.userSeq
      );
    } else {
      // send
      this.dataSource.data = this.fileInfoTotal.filter(
        fileInfo => fileInfo.info.senderSeq === this.loginRes.userSeq
      );
    }
  }

  getCheckAllUser() {
    const data = this.dataSource
      .sortData(this.dataSource.data, this.sort)
      .filter((u, i) => i >= this.paginator.pageSize * this.paginator.pageIndex)
      .filter((u, i) => i < this.paginator.pageSize);

    if (data.length === 0) {
      return false;
    }

    if (
      data.filter(
        dInfo =>
          this.selectedFileList.filter(
            fileInfo => fileInfo.info.seq === dInfo.info.seq
          ).length === 0
      ).length > 0
    ) {
      return false;
    } else {
      return true;
    }
  }
  onCheckAllkUser(value: boolean) {
    const data = this.dataSource
      .sortData(this.dataSource.data, this.sort)
      .filter((u, i) => i >= this.paginator.pageSize * this.paginator.pageIndex)
      .filter((u, i) => i < this.paginator.pageSize);

    if (!!data && data.length > 0) {
      if (value) {
        this.selectedFileList.push(
          ...data.filter(dInfo =>
            this.selectedFileList.filter(
              fileInfo => fileInfo.info.seq !== dInfo.info.seq
            )
          )
        );
      } else {
        this.selectedFileList = this.selectedFileList.filter(
          fileInfo =>
            !(
              data.filter(dInfo => dInfo.info.seq === fileInfo.info.seq)
                .length > 0
            )
        );
      }
    }
  }
  getCheckUser(fileInfo: FileInfoTotal) {
    if (this.selectedFileList) {
      if (
        this.selectedFileList.filter(
          info => info.info.seq === fileInfo.info.seq
        ).length > 0
      ) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
  onCheckUser(value: boolean, fileInfo: FileInfoTotal) {
    if (value) {
      this.selectedFileList.push(fileInfo);
    } else {
      this.selectedFileList = this.selectedFileList.filter(
        info => info.info.seq !== fileInfo.info.seq
      );
    }
  }
  onClickRow(row: FileInfoTotal) {
    this.selectedFile = row;
  }
}
