import { Component, OnInit, Inject, ViewChild } from '@angular/core';
import {
  MatDialogRef,
  MAT_DIALOG_DATA,
  MatSelectionList,
  MatSelectionListChange
} from '@angular/material';
import { Observable, combineLatest } from 'rxjs';
import { Store, select } from '@ngrx/store';
import { map } from 'rxjs/operators';

import * as AppStore from '@app/store';
import * as SyncStore from '@app/store/messenger/sync';

import {
  DialogService,
  ConfirmDialogComponent,
  ConfirmDialogData,
  ConfirmDialogResult
} from '@ucap-webmessenger/ui';
import { GroupDetailData, UserInfo } from '@ucap-webmessenger/protocol-sync';

export interface SelectGroupDialogData {
  title: string;
}

export interface SelectGroupDialogResult {
  choice: boolean;
  group?: GroupDetailData;
}

@Component({
  selector: 'app-layout-messenger-select-group',
  templateUrl: './select-group.dialog.component.html',
  styleUrls: ['./select-group.dialog.component.scss']
})
export class SelectGroupDialogComponent implements OnInit {
  constructor(
    public dialogRef: MatDialogRef<
      SelectGroupDialogData,
      SelectGroupDialogResult
    >,
    @Inject(MAT_DIALOG_DATA) public data: SelectGroupDialogData,
    private store: Store<any>,
    private dialogService: DialogService
  ) {}

  @ViewChild('groups', { static: true }) groups: MatSelectionList;
  groupBuddyList$: Observable<
    { group: GroupDetailData; buddyList: UserInfo[] }[]
  >;
  selectedGroup: GroupDetailData;
  isShowAddGroupField = false;

  ngOnInit(): void {
    this.groups.selectionChange.subscribe((s: MatSelectionListChange) => {
      this.groups.deselectAll();
      s.option.selected = true;
      this.selectedGroup = s.option.value as GroupDetailData;
    });

    this.groupBuddyList$ = combineLatest([
      this.store.pipe(
        select(AppStore.MessengerSelector.SyncSelector.selectAllBuddy2)
      ),
      this.store.pipe(
        select(AppStore.MessengerSelector.SyncSelector.selectAllGroup2)
      )
    ]).pipe(
      map(([buddyList, groupList]) => {
        const groupBuddyList: {
          group: GroupDetailData;
          buddyList: UserInfo[];
        }[] = [];
        for (const group of groupList) {
          groupBuddyList.push({
            group,
            buddyList: buddyList.filter(buddy => {
              return group.userSeqs.indexOf(buddy.seq) > -1;
            })
          });
        }

        return groupBuddyList;
      })
    );
  }

  async onClickAddGroup(groupName: string) {
    const result = await this.dialogService.open<
      ConfirmDialogComponent,
      ConfirmDialogData,
      ConfirmDialogResult
    >(ConfirmDialogComponent, {
      width: '300px',
      data: {
        title: 'Add group',
        html: `그룹(${groupName})을 추가하시겠습니까?`
      }
    });

    if (!!result && !!result.choice && result.choice) {
      if (groupName.trim().length > 0) {
        this.store.dispatch(
          SyncStore.createGroup({
            groupName: groupName.trim()
          })
        );

        this.onClickAddGroupCancel();
      }
    }
  }
  onClickAddGroupCancel() {
    this.isShowAddGroupField = false;
  }

  onClickChoice(choice: boolean): void {
    this.dialogRef.close({
      choice,
      group: this.selectedGroup
    });
  }
}
