import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  ChangeDetectorRef,
  Renderer2
} from '@angular/core';
import { ucapAnimations } from '../animations';
import { UserInfoSS } from '@ucap-webmessenger/protocol-query';
import { MatPaginator, PageEvent } from '@angular/material';
import {
  StatusBulkInfo,
  WorkStatusType
} from '@ucap-webmessenger/protocol-status';
import { StatusCode, PresenceType } from '@ucap-webmessenger/core';
import { VersionInfo2Response } from '@ucap-webmessenger/api-public';

@Component({
  selector: 'ucap-integrated-search',
  templateUrl: './integrated-search.component.html',
  styleUrls: ['./integrated-search.component.scss'],
  animations: ucapAnimations
})
export class IntegratedSearchComponent implements OnInit {
  @Input()
  profileImageRoot?: string;
  @Input()
  sessionVerinfo: VersionInfo2Response;
  @Input()
  presence?: StatusBulkInfo[] = [];
  @Input()
  searchWord?: string;
  @Input()
  searchingProcessing: boolean;
  @Input()
  searchUserInfos: UserInfoSS[] = [];
  @Input()
  totalCount = 0;
  @Input()
  pageCurrent = 1;
  @Input()
  pageListCount = 20;

  @Output()
  search = new EventEmitter<string>();
  @Output()
  changePage = new EventEmitter<PageEvent>();
  @Output()
  openProfile = new EventEmitter<number>();

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  displayedColumns: string[] = [
    'profile',
    'deptName',
    'companyName',
    'grade',
    'lineNumber',
    'hpNumber',
    'email',
    'responsibilities',
    'workplace'
  ];

  start: any = undefined;
  pressed = false;
  startX: any;
  startWidth: any;
  relationWidth: any;
  resizableFnMousemove: () => void;
  resizableFnMouseup: () => void;

  PresenceType = PresenceType;

  constructor(
    private changeDetectorRef: ChangeDetectorRef,
    private renderer: Renderer2
  ) {}

  ngOnInit() {
    this.profileImageRoot =
      this.profileImageRoot || this.sessionVerinfo.profileRoot;
  }

  onSearch(keyword: string) {
    this.search.emit(keyword);
  }

  onChangePage(event: PageEvent) {
    this.changePage.emit(event);
  }

  getPresence(userInfo: UserInfoSS, type: PresenceType): string {
    const presences = this.presence.filter(p => p.userSeq === userInfo.seq);

    let status: string;
    let rtnClass = '';
    if (!!presences && presences.length > 0) {
      const presence = presences[0];
      switch (type) {
        case PresenceType.PC:
          status = !!presence ? presence.pcStatus : undefined;
          break;
        case PresenceType.MOBILE:
          status = !!presence ? presence.mobileStatus : undefined;
          break;
      }

      if (!!status) {
        switch (status) {
          case StatusCode.OnLine:
            rtnClass = type + 'On';
            break;
          case StatusCode.Away:
            rtnClass = type + 'Out';
            break;
          case StatusCode.Busy:
            rtnClass = type + 'Other';
            break;
          default:
            rtnClass = type + 'Off';
            break;
        }
      }
    } else {
      rtnClass = type + 'Off';
    }

    return rtnClass;
  }
  getPresenceMsg(userInfo: UserInfoSS): string {
    const presences = this.presence.filter(p => p.userSeq === userInfo.seq);

    if (!!presences && presences.length > 0) {
      const presence = presences[0];
      if (
        !!presence &&
        !!presence.statusMessage &&
        presence.statusMessage !== '.'
      ) {
        return presence.statusMessage;
      }
    }
    return '';
  }
  getWorkstatusInfo(userInfo: UserInfoSS, type: string): string {
    let workstatus = userInfo.workstatus;

    const presences = this.presence.filter(p => p.userSeq === userInfo.seq);

    if (!!presences && presences.length > 0) {
      const presence = presences[0];
      if (
        !!presence &&
        !!presence.workstatus &&
        presence.workstatus.trim().length > 0
      ) {
        workstatus = presence.workstatus;
      }
    }

    let text = '';
    // morning-off: 오전 afternoon-off: 오후  day-off: 휴가 long-time: 장기  leave-of-absence: 휴직
    let style = '';
    switch (workstatus) {
      case WorkStatusType.VacationAM:
        style = 'morning-off';
        text = '오전';
        break;
      case WorkStatusType.VacationPM:
        style = 'afternoon-off';
        text = '오후';
        break;
      case WorkStatusType.VacationAll:
        style = 'day-off';
        text = '휴가';
        break;
      case WorkStatusType.LeaveOfAbsence:
        style = 'leave-of-absence';
        text = '휴직';
        break;
      case WorkStatusType.LongtermRefresh:
        style = 'long-time';
        text = '장기';
        break;
    }

    return type === 'text' ? text : style;
  }

  onClickOpenProfile(event: MouseEvent, userSeq: number) {
    event.preventDefault();
    event.stopPropagation();

    this.openProfile.emit(userSeq);
  }

  resizeTable(event: any) {
    this.start = event.target;
    if (this.start.cellIndex !== this.displayedColumns.length - 1) {
      this.pressed = true;
      this.startX = event.pageX;
      this.startWidth = this.start.clientWidth;
      this.relationWidth = this.start.nextElementSibling.clientWidth;
      this.mouseMove();
    }
  }

  mouseMove() {
    const column = this.start;
    const relationColumn = column.nextElementSibling;

    this.resizableFnMousemove = this.renderer.listen(
      'document',
      'mousemove',
      event => {
        if (this.pressed) {
          const gap = event.pageX - this.startX;
          const columnWidth = this.startWidth + gap;
          const relationWidth = this.relationWidth - gap;

          if (columnWidth > 50 && relationWidth > 50) {
            column.width = columnWidth;
            relationColumn.width = relationWidth;
          }
        }
      }
    );
    this.resizableFnMouseup = this.renderer.listen(
      'document',
      'mouseup',
      event => {
        if (this.pressed) {
          this.pressed = false;
          this.start = undefined;
          this.startX = undefined;
          this.startWidth = undefined;
          this.relationWidth = undefined;
          this.resizableFnMousemove();
          this.resizableFnMouseup();
        }
      }
    );
  }
}
