import {Component, Input} from '@angular/core';
import {Router} from "@angular/router";
import {PagesService} from "@app/_services/pages.service";
import {FormsService, ListsService} from "@app/_services";
import {Subscription} from "rxjs";
import {SortableOptions} from "sortablejs";

@Component({
  selector: 'pages-tree',
  templateUrl: 'pages-tree.component.html',
  styleUrls: ['pages-tree.component.scss']
})
export class PagesTreeComponent {
  @Input() parent: any;
  public pages = <any>[];
  subscription: Subscription;

  public options: SortableOptions = {
    group: 'site-pages',
    handle: '.move',
    onUpdate: (event: any) => {
      this.move(event);
    },
    onAdd: (event: any) => {
      this.move(event);
    }
  };


  constructor(private router: Router, private pagesService: PagesService, private listsService: ListsService, private formsService: FormsService) {
  }

  get listId() {
    return 'pages-tree-root';
  }

  ngOnInit() {
    if (!this.parent) this.subscription = this.listsService.controls(this.listId).subscribe(res => {
      this.fetch();
    });
  }

  ngOnChanges() {
    this.pages = this.parent?.children?.data;
  }

  ngOnDestroy() {
    this.subscription?.unsubscribe();
  }

  fetch() {
    this.parent ? this.fetchSubpages() : this.fetchRootPages();
  }

  fetchRootPages() {
    let include = ['children'];
    this.pagesService.root({include: include}).subscribe(res => {
      this.pages = res.data;
    });
  }

  fetchSubpages() {
    let include = ['children.children.children.children.children.children.children'];
    this.pagesService.show(this.parent.id, {include: include.join(',')}).subscribe(res => {
      this.pages = res.data?.children?.data;
    });
  }


  add() {
    this.formsService.createModel('page', null, this.listId);
  }


  move(event: any) {
    this.pagesService.move(event.item.id, {parent: this.parent?.id, ord: event.newIndex}).subscribe(res => {
      this.pagesService.changedPages();
    });
  }


}
