import { Component, ChangeDetectionStrategy, Input, OnChanges, SimpleChanges, HostBinding } from '@angular/core';
import { DomainTaskCalendarService } from '@domain/task-calendar';
import { DisplayInfoDTO } from '@swagger/eis';
import { combineLatest, ReplaySubject } from 'rxjs';
import { catchError, map, shareReplay, switchMap } from 'rxjs/operators';

@Component({
  selector: 'page-task-list-item',
  templateUrl: 'task-list-item.component.html',
  styleUrls: ['task-list-item.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TaskListItemComponent implements OnChanges {
  @Input()
  item: DisplayInfoDTO;

  @Input()
  showDate = true;

  item$ = new ReplaySubject<DisplayInfoDTO>();

  itemType$ = this.item$.pipe(
    map((item) => this.domainTaskCalendarService.getInfoType(item)),
    shareReplay()
  );

  isPreInfo$ = this.itemType$.pipe(map((type) => type === 'PreInfo'));

  isTask$ = this.itemType$.pipe(map((type) => type === 'Task'));

  isInfo$ = this.itemType$.pipe(map((type) => type === 'Info'));

  isInfoOrPreInfo$ = combineLatest([this.isInfo$, this.isPreInfo$]).pipe(map(([info, preInfo]) => info || preInfo));

  hasComments$ = this.item$.pipe(map((item) => item.comments > 0));

  hasIcon$ = combineLatest([this.isInfoOrPreInfo$, this.hasComments$]).pipe(map(([infoOrPreInfo, comments]) => infoOrPreInfo || comments));

  indicatorColor$ = this.item$.pipe(map((item) => this.domainTaskCalendarService.getProcessingStatusColorCode(item)));

  hasAttachments$ = this.item$.pipe(map((info) => info.attachments > 0 || info.articles?.length > 0));

  showTime$ = this.item$.pipe(map((item) => !!item?.timeFrom && !!item?.timeTo));

  processingStatus$ = this.item$.pipe(
    map((info) => this.domainTaskCalendarService.getProcessingStatusList(info)),
    shareReplay()
  );

  showUpdateIcon$ = combineLatest([this.processingStatus$, this.item$]).pipe(
    map(([processingStatus, info]) => (info.successor && processingStatus.includes('Removed')) || info.predecessor)
  );

  hasUpdate$ = this.item$.pipe(map((item) => !!item.successor));

  @HostBinding('class')
  get completed() {
    return this.domainTaskCalendarService.getProcessingStatusList(this.item);
  }

  constructor(private domainTaskCalendarService: DomainTaskCalendarService) {}

  ngOnChanges({ item }: SimpleChanges): void {
    if (item) {
      this.item$.next(this.item);
    }
  }
}
