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


@Component({
  selector: 'left-content',
  templateUrl: html.leftContent||'./left-content.component.html',
  styleUrls: ['./left-content.component.scss']
})
export class LeftContentComponent {

  public url: string = "";
  public background:string;
  public pageName:string;
  public editable:string;
  public editMode: boolean = false;
  private pageID: string;
  private routeSubscription: Subscription;



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

  ngOnInit(){
    this.routeSubscription = this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) this.onNavigationEnd(event);
    });
    this.pagesService.editMode.subscribe(
      mode => {
        this.editMode = mode;
      }
    )
  }

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

  fetch(){
    let include = [
      'permissions',
      'parents'
    ];
    this.pagesService.find(this.url, {include: include.join(',')}).subscribe(
      resp => {
        let page = resp?.data;
        if (page){
          this.background = page.image?.data?.links?.full;
          if (this.background) this.background = `url(${this.background})`;
          this.pageName = (page.parents.data[2]||page).name;
          this.editable = page.permissions.edit || page.permissions.anything;
          this.pageID = page.id
        }else{
          this.pageName = null;
          this.editable = null;
          this.pagesService.editMode.next(false)
        }
      }
    )
  }

  toggleEditMode(){
    this.pagesService.editMode.next(!this.editMode)
  }

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

  removeBackground() {
    if (confirm('Вы деествительно хотите удалить этот фон?')) {
      this.pagesService.deleteBackground(this.pageID).subscribe(res => {
      });
    }
  }

}

 

