import {Component} from '@angular/core';
import {NavigationEnd, Router} from "@angular/router";
import {Subscription} from "rxjs";
import {PagesService} from "@app/_services/pages.service";
import {FormsService, 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,
    private formsService: FormsService) {
    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;
  }
  get pageTopName(){
    return this.page?.parents?.data[2]?.name;
  }



  ngOnInit() {
    this.listsService.controls().subscribe(res => {
      this.inited ? this.fetch() : this.inited = true;
    });
  }

  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.editMode = false;
    }
  }

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

  toggleEditMode() {
    this.editMode = !this.editMode;
  }

  editBackground() {
    this.formsService.createModel('page-background', {extraProps: {attach: {pageId: this.page.id}}});
  }

  removeBackground() {
    if (confirm('Вы деествительно хотите удалить этот фон?')) {
      this.pagesService.deleteBackground(this.page.id).subscribe(res => {
        //console.log(res);
      //  this.listsService.refresh(this.listId, true);
      });
    }
  }
}
