import { Component, inject, signal, OnDestroy, OnInit } from '@angular/core';
import { Router, RouterModule } from '@angular/router';
import { Subject, takeUntil } from 'rxjs';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

import SharedModule from 'app/shared/shared.module';
import { AccountService } from 'app/core/auth/account.service';
import { Account } from 'app/core/auth/account.model';
import { HomeService } from './service/home.service';

@Component({
  standalone: true,
  selector: 'jhi-home',
  templateUrl: './home.component.html',
  styleUrl: './home.component.scss',
  imports: [SharedModule, RouterModule],
})
export default class HomeComponent implements OnDestroy, OnInit {
  account = signal<Account | null>(null);
  htmlPage: SafeHtml = "";

  private readonly destroy$ = new Subject<void>();

  private homeService = inject(HomeService);
  private accountService = inject(AccountService);
  private router = inject(Router);
  private sanitizer = inject(DomSanitizer);

  ngOnInit(): void {
    this.accountService
      .getAuthenticationState()
      .pipe(takeUntil(this.destroy$))
      .subscribe(account => { 
        this.htmlPage = this.sanitizer.bypassSecurityTrustHtml("");
        this.account.set(account); 

        // Load HOME PAGE
        this.homeService.homePage().subscribe((html) => { 
          const rawHtml = html.body ?? ""; 
          this.htmlPage = this.sanitizer.bypassSecurityTrustHtml(rawHtml);
        });
      });
    
    // Load HOME PAGE
    this.homeService.homePage().subscribe((html) => { 
      const rawHtml = html.body ?? ""; 
      this.htmlPage = this.sanitizer.bypassSecurityTrustHtml(rawHtml);
    });
  
  }

  login(): void {
    this.router.navigate(['/login']);
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
