import {Component, Input} from '@angular/core';
import {Subscription} from "rxjs";
import {FormsService, ListsService} from "@app/_services";
import {PublicationsService} from "@app/_services/publications.service";

@Component({
  selector: 'publications-list',
  templateUrl: 'list.component.html',
  styleUrls: ['list.component.scss']
})
export class PublicationsListComponent {
  @Input() page: any;
  @Input() editMode: boolean;

  controlsSubscription?: Subscription;
  resultsSubscription?: Subscription;

  public result: any;

  constructor(private publicationsService: PublicationsService, private listsService: ListsService, private formsService: FormsService) {
  }

  get listId() {
    return 'publications-list';
  }

  ngOnInit() {
    this.controlsSubscription = this.listsService.controls(this.listId).subscribe(controls => {
      this.fetch(controls);
    });
    this.resultsSubscription = this.listsService.result(this.listId).subscribe(val => {
      this.result = val;
    });
  }

  ngOnChanges() {
    this.listsService.result(this.listId).next(null);
    this.listsService.setFilters({page: this.page?.id}, this.listId);
  }

  ngOnDestroy() {
    this.controlsSubscription?.unsubscribe();
    this.resultsSubscription?.unsubscribe();
  }


  get items() {
    return this.result?.data;
  }


  add() {
    this.formsService.createModel(this.page.subType, {extraProps: {attach: {pageId: this.page.id}}}, this.listId);
  }

  fetch(controls) {
    let params = {page: controls.page || 0, filters: JSON.stringify(controls.filters), pageId: this.page?.id || null};
    this.publicationsService.list(params).subscribe(result => {
      this.listsService.result(this.listId).next(result);
    })
  }
}
