// Angular Core
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { UpperCasePipe, ViewportScroller } from '@angular/common';

// RxJs
import { Subscription, throwError } from 'rxjs';
import { catchError, filter } from "rxjs/operators";

// Services
import { ContentService } from 'src/app/services/content/content.service';
import { SessionService } from 'src/app/services/session/session.service';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';

@Component({
  standalone: false,
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.scss']
})
export class ContentComponent implements OnInit, OnDestroy {

  topicTitle!: string;
  topicContent!: string;
  renderMe: boolean = false;
  sitename!: string;
  sitenameListener!: Subscription;
  routerListener!: Subscription;

  constructor(
    private contentService:ContentService,
    private router : Router,
    private activatedRoute: ActivatedRoute,
    private sessionService : SessionService,
    private titleService: Title,
    private viewportScroller: ViewportScroller,
    private dataTransmitter: DataTransmitterService
  ) { 
    this.sessionService.getAuth().then((response) => {
      this.renderMe = true;
    });
  }

  ngOnInit(): void {
    this.routerListener = this.router.events.pipe (
        filter(event => event instanceof NavigationEnd),
    ).subscribe(() => {
        this.viewportScroller.scrollToPosition([0, 0]);
        this.getPage();
  });
    this.sitenameListener = this.dataTransmitter.sitename.subscribe((sitename) => {
      this.sitename = sitename;
    });
    this.getPage();
  }

  getContentSubscribe!:Subscription;

  getPage(){
    let pageHandle: string = this.activatedRoute.snapshot.paramMap.get('pageHandle') || '';
    let upperCase = new UpperCasePipe();
    this.titleService.setTitle(this.sitename + ' | '+ upperCase.transform(pageHandle))
    this.getContentSubscribe = this.contentService.getContent(pageHandle)
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: (res: any) => {
          let content:any = Object.values(res.data[0]['Page Handle'][pageHandle])[0];
          this.topicTitle = content.topic_name;
          this.topicContent = content.topic_content;
        },
        error: (err) => {
          this.contentService.errorCallBack(err);
        },
        complete: () => { },
      })
  }

  ngOnDestroy(){
    this.getContentSubscribe?.unsubscribe();
    this.routerListener?.unsubscribe();
    this.sitenameListener.unsubscribe();
  }

}
