import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {environment} from '@environments/environment';
import {Observable, BehaviorSubject} from "rxjs";


@Injectable({providedIn: 'root'})
export class PagesService {
  public currentPageSubject = new BehaviorSubject<any>(null);
  public rootPageSubject = new BehaviorSubject<any>(null);
  public metaSubject = new BehaviorSubject<any>({title: '', description: '', keywords: ''});
  public editMode = new BehaviorSubject<boolean>(false);

  constructor(private http: HttpClient) {
    //this.find('/').subscribe(res => {this.rootPage = res.data});
  }

  get currentPage() {
    return this.currentPageSubject.value;
  }
  set currentPage(val: any) {
    this.currentPageSubject.next(val);
    this.rootPage = val?.parents?.data[0] || val;
    this.setMetaFromPage(val);
  }
  get rootPage() {
    return this.rootPageSubject.value;
  }
  set rootPage(val: any) {
    this.rootPageSubject.next(val);
  }



  root(params?: {}): Observable<any> {
    return this.http.get(`${environment.apiUrl}/api/pages/root`, {params: params});
  }

  find(url: string, params?: any): Observable<any> {
    if (!params) params = {};
    params.url = url;
    return this.http.get(`${environment.apiUrl}/api/pages/find`, {params: params});
  }

  list(params?: {}): Observable<any> {
    return this.http.get(`${environment.apiUrl}/api/pages`, {params: params});
  }

  show(id: string, params?: {}): Observable<any> {
    return this.http.get<any>(`${environment.apiUrl}/api/pages/${id}`, {params: params});
  }

  delete(id: string): Observable<any> {
    return this.http.delete(`${environment.apiUrl}/api/pages/${id}`);
  }

  deleteBackground(id: string): Observable<any> {
    return this.http.delete(`${environment.apiUrl}/api/pages/background/${id}`);
  }

  move(id: string, data: any): Observable<any> {
    return this.http.put(`${environment.apiUrl}/api/pages/${id}`, data);
  }


  setMetaFromPage(page: any) {
    this.setMeta({title: page?.title || page?.name, description: page?.description || '', keywords: page?.keywords || ''});
  }
  setMeta(meta: any) {
    this.metaSubject.next(meta);
  }
}
