//import { Component, OnInit, OnDestroy } from '@angular/core';
import { Component, OnInit, OnDestroy, inject, ChangeDetectorRef, signal, output } from '@angular/core';
import { catchError, EMPTY, finalize, Subscription } from 'rxjs';
import { CommonUtilities, HttpUtility, LookupService } from '../shares';
import { DialogService ,DynamicDialogConfig,DynamicDialogModule, DynamicDialogRef} from 'primeng/dynamicdialog';
import { ConfirmationService, MessageService } from 'primeng/api';
import { AddPhoto } from './add.photo';
import { PersonPhotoDto } from '../models';

import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { TooltipModule } from 'primeng/tooltip';
import { AuthenticationService } from '../user-services';
import { HttpResponse } from '@angular/common/http';
import { PersonService } from '../person';

@Component({
    selector: 'photo-list',
    imports: [CommonModule, FormsModule, DynamicDialogModule,TooltipModule,
        ButtonModule, TableModule],
    templateUrl: './photolist.html',
    styleUrls: ['./photolist.css'],
    providers: [DialogService]
})
export class PhotoList implements OnInit, OnDestroy {
  FileList: PersonPhotoDto[] =[]
  loading = false;
  _id = -1;
  deletePersonPhoto: number[] = [];
  private authenticationService = inject(AuthenticationService);
  private cdr = inject(ChangeDetectorRef);
  private confirmationService = inject(ConfirmationService);
  private messageService = inject(MessageService);
  private subscription: Subscription = new Subscription();
  downloadFile = signal(false);
  constructor(
    private http: HttpUtility,
    private personService: PersonService,
   
    public ref: DynamicDialogRef, public config: DynamicDialogConfig,
    public dialogService: DialogService
  ) { }

  ngOnInit(): void {
    const id = this.config.data.id;
    const olist = this.config.data.personPhotos;
    if (olist && olist.length > 0)
    {
      this.FileList = olist;
      this.assignFileId(olist);
    }
  }
  assignFileId(files: any[]): void {
    let i = 0;
    let id = -1;
    let mx = 1;
    for (i = 0; i < files.length; i++)
    {
      id = files[i].id;
      if (id < mx)
      {
        mx = id;
      }
    }
    this._id = -1 + mx;
  }
  downloadAttachment(id: number): void {
    //GetReportFile
    
    let typeofCall = "personId_" + id.toString();
    
    let criteria:any ={id, fileName:''};
    this.downloadFile.set(false);
    this.http.getFileResponse("api/FileUpload/downloadPersonPhoto", criteria).pipe(
      catchError(err => {
        console.error(err.message);
        return EMPTY;
      }),
      finalize(() => {
        // this.toastr.success("download completed ok to view now");
        this.downloadFile.set(false);
     
      })).subscribe((response: HttpResponse<Blob>) => {
        if (response) {
          console.log("the download report response", response);
          CommonUtilities.downloadFile(response, typeofCall);
        }
      });
  }

onClose(event: Event): void {
  const nlist = this.FileList.filter( x => x.id < 1);
  this.ref.close({list: nlist, deleteIds: this.deletePersonPhoto});
}
newSupportDoc(event: Event): void {
  this.showEdit(this._id--);
}
remove(id: number): void {
   this.confirmationService.confirm({
            
            message: 'Do you want to delete this record?',
            header: 'Confirmation Delete',
            icon: 'pi pi-info-circle',
            rejectLabel: 'Cancel',
            rejectButtonProps: {
                label: 'Cancel',
                severity: 'secondary',
                outlined: true,
            },
            acceptButtonProps: {
                label: 'Delete',
                severity: 'danger',
            },

            accept: () => {
                this.doRemove(id);
            }
          });
}
doRemove(id: number): void {
  if (id < 0)
  {
    const nlist = this.FileList.filter(x => x.id != id);
    this.FileList = [...nlist];
    this.cdr.markForCheck();
  }
  else
  {
    const deletepersonPhoto$ = this.personService.deletePersonPhotoFile(id);
    this.subscription.add(deletepersonPhoto$.subscribe(
      {
        next: x => {
          if (x.statusCode == 1)
          {
            const nlist = this.FileList.filter(x => x.id != id);
            this.FileList = [...nlist];
            this.deletePersonPhoto.push(id);            
            this.cdr.markForCheck();
            this.messageService.add({severity:'success', summary: 'delete person photo', detail: "person photo Id " + id });
          }
        },
        error:e => console.error("error in client delete person photo", e)
      }
    ));
  }
  
  
  
}
  showEdit(id: number) {
    const ref = this.dialogService.open(AddPhoto, {
      data: {
        id,      
      },
      header: 'Add File',
      width: '70%',
      maximizable: true,
      draggable: true
    });
    if (ref)
    {
      ref.onClose.subscribe((list: File[]) => {
      if (list) {
        //console.log("after close ward edit", item);
        this.messageService.add({ severity: 'success', summary: 'Attact File', detail: list.length.toString() });
        let it = id;
        for (let i = 0; i < list.length; i++)
        {
          const item = list[i];
          this.FileList.push({id: it--, photo: item.name, photoType:'', file: item});
        }
        this.cdr.markForCheck();
      }
    });
    }
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
