import { Component, inject, OnDestroy, OnInit, signal } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { AppSettingService } from '../shares';
import { PersonService } from '../person';
import { Subscription } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { CommonModule } from '@angular/common';
import { ButtonModule } from 'primeng/button';
import { DynamicDialogConfig, DynamicDialogRef } from 'primeng/dynamicdialog';

@Component({
  selector: 'app-image-display',
  imports:[CommonModule, ButtonModule],
  templateUrl: './image.display.html',
  styleUrls: ['./image.display.css']
})
export class ImageDisplayComponent implements OnInit, OnDestroy {
  //base64ImageString: string = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='; // Example Base64 (a tiny red dot PNG)
  //imageDataUrl: SafeResourceUrl ={};
  imageDataUrl = signal<string>("");
  private personService = inject(PersonService);
  private sanitizer = inject(DomSanitizer);
  //private route = inject(ActivatedRoute);
  public ref = inject(DynamicDialogRef); 
  public config = inject(DynamicDialogConfig);
  private subscription:Subscription = new Subscription();

 ngOnInit(): void {
    
     const imageName = this.config.data.imageName;   
    this.loadImage(imageName);

  }
  loadImage(fileName: string| null): void {
    const download = this.personService.downloadFile(fileName!);
    this.subscription.add(download.subscribe({
      next: x => {
        if (x.statusCode == 1)
        {
          this.display(x.data);
          console.log("this is show image" , this.imageDataUrl(), x);
        }
        else
        {
          console.log("error in download in api ", x.message);
        }
      },
      error: e => console.error("error in download image", e)
    }));
  }
  display(baseImage: string): void 
  { 
    const changeUrl = (this.sanitizer.bypassSecurityTrustResourceUrl(baseImage) as any).changingThisBreaksApplicationSecurity;
    console.log('this is bypassSecurityTrustResourceUrl', changeUrl);
    const fullDataUri = `data:image/png;base64,${changeUrl}`;
    this.imageDataUrl.set(fullDataUri);
  }
  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
  close() :void {
     this.ref.close(null);
  }
}