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";

@Component({
  selector: 'pages-tree-item',
  templateUrl: 'pages-tree-item.component.html',
  styleUrls: ['../pages-tree.component.scss', 'pages-tree-item.component.scss']
})
export class PagesTreeItemComponent {
  @Input() page: any;
  @Input() parent: any;
  public active = false;
  public touched = false;
  public subscription: Subscription;

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

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


  get listId() {
    return this.page.id;
  }

  get parentListId() {
    return this.parent?.id || 'pages-tree-root';
  }

  get logo() {
    return this.page?.logo?.data.links?.full;
  }

  get noLogoLetters() {
    return this.page.name.replace(' ', '').slice(0, 2);
  }

  get children() {
    return this.page.children?.data;
  }


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

  add() {
    this.formsService.createModel('page', {extraProps: {parent: this.page.id}}, this.listId);
    this.active = true;
  }

  edit() {
    this.formsService.editModel('page', this.page.id, null, this.listId);
  }

  delete() {
    if (confirm('r u sure?')) this.pagesService.delete(this.page.id).subscribe(res => {
      this.listsService.refresh(this.parentListId);
      this.pagesService.changedPages();
    });
  }

  toggle() {
    this.active = !this.active;
    if (this.active) this.fetch();
  }
}
