import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  ContentChild,
  TemplateRef
} from '@angular/core';

import { ucapAnimations } from '@ucap-webmessenger/ui';

import { GroupDetailData, UserInfo } from '@ucap-webmessenger/protocol-sync';
import { MatAccordion } from '@angular/material';
import { ExpansionPanelItemDirective } from '../directives/expansion-panel-item.directive';
import {
  UserInfoSS,
  UserInfoF,
  UserInfoDN
} from '@ucap-webmessenger/protocol-query';
import { NGXLogger } from 'ngx-logger';

@Component({
  selector: 'ucap-group-expansion-panel',
  templateUrl: './expansion-panel.component.html',
  styleUrls: ['./expansion-panel.component.scss'],
  animations: ucapAnimations
})
export class ExpansionPanelComponent implements OnInit {
  @Input()
  groupBuddyList: { group: GroupDetailData; buddyList: UserInfo[] }[];
  @Input()
  favoritBuddyList?: UserInfo[];
  @Input()
  myProfileInfo?: UserInfo;
  @Input()
  checkable = false;
  @Input()
  /** 선택된 사용자의 리스트 */
  selectedUserList?: (UserInfo | UserInfoSS | UserInfoF | UserInfoDN)[] = [];

  @Output()
  more = new EventEmitter<{
    event: MouseEvent;
    group: GroupDetailData;
  }>();

  @Output()
  checkGroup = new EventEmitter<{
    isChecked: boolean;
    groupBuddyList: { group: GroupDetailData; buddyList: UserInfo[] };
  }>();

  @ContentChild(ExpansionPanelItemDirective, {
    read: TemplateRef,
    static: true
  })
  expansionPanelItemTemplateRef: TemplateRef<ExpansionPanelItemDirective>;

  @ViewChild('groupAccordion', { static: true }) groupAccordion: MatAccordion;

  constructor(private logger: NGXLogger) {}

  ngOnInit() {}

  expandMore() {
    this.groupAccordion.openAll();
  }

  expandLess() {
    this.groupAccordion.closeAll();
  }

  onClickMore(event: MouseEvent, group: GroupDetailData) {
    this.more.emit({ event, group });
  }

  /** 그룹리스트가 checkable 할 경우 checkbox 의 change 이벤트를 상위 컴포넌트로 전달한다. */
  onChangeCheck(
    value: boolean,
    groupBuddyList: { group: GroupDetailData; buddyList: UserInfo[] }
  ) {
    this.checkGroup.emit({
      isChecked: value,
      groupBuddyList
    });
  }

  /** 그룹리스트가 checkable 할 경우 checkbox 의 isChecked 를 관장하며, 하위 부서원들의 전체선택여부를 판단한다. */
  getCheckedGroup(groupBuddy: {
    group: GroupDetailData;
    buddyList: UserInfo[];
  }) {
    if (groupBuddy.buddyList.length === 0) {
      return false;
    }
    if (!!this.selectedUserList && this.selectedUserList.length > 0) {
      let allExist = true;
      groupBuddy.buddyList.some(groupUser => {
        if (
          this.selectedUserList.filter(item => item.seq === groupUser.seq)
            .length === 0
        ) {
          allExist = false;
          return true;
        }
      });
      return allExist;
    }
    return false;
  }
}
