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

@Component({
  templateUrl: 'page.component.html',
  styleUrls: ['page.component.scss']
})
export class PageComponent {
  public page: any;
  public editMode: boolean;
  public loading = false;
  private url: string;
  private inited = false;
  routeSubscription?: Subscription;
  subscription: Subscription;

  constructor(
    private router: Router,
    private pagesService: PagesService,
    private listsService: ListsService) {
    this.routeSubscription = this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) this.onNavigationEnd(event);
    });
  }



  get permissions() {
    return this.page?.permissions;
  }

  get isEditable() {
    return this.permissions?.edit || this.permissions?.anything;
  }


  ngAfterContentInit() {
    this.listsService.controls().subscribe(res => {
      this.inited ? this.fetch() : this.inited = true;
    });
    this.pagesService.editMode.subscribe(
      mode=>this.editMode = mode
    )
  }

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

  onNavigationEnd(event: NavigationEnd) {
    let url = event.url.split('(')[0];
    url = url.split('?')[0];
    if (url !== this.url) {
      this.url = url;
      this.fetch();
      this.pagesService.editMode.next(false);
    }
  }

  fetch() {
    this.loading = true;
    let include = [
      'parents.children',
      'children',
      'sections.type',
      'sections.groups.fields.value',
      'sections.objects.groups.fields.value',
      'sidebars.groups.fields.value',
      'sidebars.type',
      'permissions',
      'picture'
    ];
    this.pagesService.find(this.url, {include: include.join(',')}).subscribe(res => {
      this.page = res?.data;
      if (this.page) this.pagesService.currentPage = this.page;
      this.loading = false;
    }, error => {
      this.loading = false;
    });
  }
}
