import { DatePipe } from '@angular/common';
import { Component, ChangeDetectionStrategy, Input, EventEmitter, Output } from '@angular/core';
import { ApplicationService } from '@core/application';
import { ComponentStore } from '@ngrx/component-store';
import { ItemDTO } from '@swagger/cat';
import { DateAdapter } from '@ui/common';
import { isEqual } from 'lodash';
import { ArticleSearchService } from '../article-search.store';

export interface SearchResultItemComponentState {
  item?: ItemDTO;
  selected: boolean;
  selectable: boolean;
}

@Component({
  selector: 'search-result-item',
  templateUrl: 'search-result-item.component.html',
  styleUrls: ['search-result-item.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [DatePipe],
})
export class SearchResultItemComponent extends ComponentStore<SearchResultItemComponentState> {
  @Input()
  get item() {
    return this.get((s) => s.item);
  }
  set item(item: ItemDTO) {
    if (!isEqual(this.item, item)) {
      this.patchState({ item });
    }
  }

  readonly item$ = this.select((s) => s.item);

  @Input()
  get selected() {
    return this.get((s) => s.selected);
  }
  set selected(selected: boolean) {
    if (this.selected !== selected) {
      this.patchState({ selected });
    }
  }
  readonly selected$ = this.select((s) => s.selected);

  @Input()
  get selectable() {
    return this.get((s) => s.selectable);
  }
  set selectable(selectable: boolean) {
    if (this.selectable !== selectable) {
      this.patchState({ selectable });
    }
  }

  @Output()
  selectedChange = new EventEmitter<boolean>();

  get contributors() {
    return this.item?.product?.contributors?.split(';').map((val) => val.trim());
  }

  get publicationDate() {
    if (!!this.item?.product?.publicationDate) {
      const date = this._dateAdapter.parseDate(this.item.product.publicationDate);

      if (this._dateAdapter.getDate(date) === 1 && this._dateAdapter.getMonth(date) === 0) {
        return this._datePipe.transform(date, 'y');
      }

      return this._datePipe.transform(date, 'dd. MMMM y');
    }
    return '';
  }

  constructor(
    private _dateAdapter: DateAdapter,
    private _datePipe: DatePipe,
    private _articleSearchService: ArticleSearchService,
    public applicationService: ApplicationService
  ) {
    super({
      selected: false,
      selectable: false,
    });
  }

  setSelected(selected: boolean) {
    this._articleSearchService.setSelected({ selected, itemId: this.item?.id });
  }
}
