import { Component, input, inject, OnInit, signal } from '@angular/core';
import { RouterModule, Router, ActivatedRoute } from '@angular/router';
import { HttpResponse } from '@angular/common/http';
import { finalize, map } from 'rxjs/operators';
import { NgbDropdownModule, NgbModal } from '@ng-bootstrap/ng-bootstrap';

import SharedModule from 'app/shared/shared.module';
import { DurationPipe, FormatMediumDatetimePipe, FormatMediumDatePipe } from 'app/shared/date';
import { IPeriod, NewPeriod } from '../period.model';
import { PeriodStatus } from 'app/entities/enumerations/period-status.model';
import { IActivityInfo } from 'app/resilient/resilient-activity/resilient-activity.model';
import { ResilientActivityService } from 'app/resilient/resilient-activity/service/resilient-activity.service';
import { ResilientActivityActionsButtonComponent } from 'app/resilient/resilient-activity/actions-button/resilient-activity-actions-button.component';
import { ResilientActivityProgressComponent } from 'app/resilient/resilient-activity/progress/resilient-activity-progress.component';
import { PeriodService } from '../service/period.service';
import { AbstractResilientEntityComponent } from 'app/entities/resilient/resilient-entity.component';

import { BaseDetailLayoutComponent } from 'app/layouts/base-detail/base-detail.component'
import { ResilientLogLogsDialogComponent } from 'app/entities/resilient/log/logs-dialog/resilient-log-logs-dialog.component';

@Component({
  standalone: true,
  selector: 'jhi-period-detail',
  templateUrl: './period-detail.component.html',
  imports: [
    SharedModule, 
    RouterModule, 
    DurationPipe, 
    FormatMediumDatetimePipe, 
    FormatMediumDatePipe,
    NgbDropdownModule,
    ResilientActivityActionsButtonComponent,
    ResilientActivityProgressComponent,
    BaseDetailLayoutComponent
  ],
})
export class PeriodDetailComponent extends AbstractResilientEntityComponent<IPeriod, NewPeriod, PeriodService> implements OnInit {
  period = input<IPeriod | null>(null);
  currentTab: string = "versions";
  
  activityCollection: IActivityInfo[] = [];
  public PeriodStatus = PeriodStatus;
  
  protected resilientActivityService = inject(ResilientActivityService);
  protected router = inject(Router);
  protected route = inject(ActivatedRoute);
  protected periodService = inject(PeriodService);
  protected modalService = inject(NgbModal);

  constructor(
    service: PeriodService
  ) { super(service); }
  
  ngOnInit(): void {
    this.loadActivitiesForActivityDomain();
  }
  
  previousState(): void {
    window.history.back();
  }
  
  setTab(tab: string): void {
	  this.currentTab = tab;
  }
  
  handleActivityInvoked(event: string): void {
    this.reloadPage();
  }
  
  protected loadActivitiesForActivityDomain(): void {
    this.resilientActivityService
      .activityInfo("com.oguerreiro.resilient.domain.Period", PeriodStatus[this.period()?.state!])
      .pipe(map((res: HttpResponse<IActivityInfo[]>) => res.body ?? []))
      .subscribe((activities: IActivityInfo[]) => (this.activityCollection = activities));
  }

  /* Refresh the current record. Probably something was invoked in the server and the record mus be updated */
  reloadPage(): void {
    this.refreshPage();
  }
  
  refreshPage(): void {
    // Get the current entity ID from the route
    const entityId = this.route.snapshot.params['id'];

    // Navigate to the same detail page with the same ID
    const currentUrl: string = this.router.url;
    this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
      // this.router.navigate(['/period', entityId, 'view']);
      this.router.navigateByUrl(currentUrl);
    });
  }
  
  reloadDomain(): void {
    let id: number;
    
    if (!this.period()?.id)
      return;
    id = this.period()!.id;
    
    this.periodService
      .find(id)
      /* .pipe(map((res: HttpResponse<IActivityInfo[]>) => res.body ?? [])) */
      .subscribe((res: HttpResponse<IPeriod>) => {
        const period: IPeriod | null = res.body ?? null;
        // this.period = of(period);
      });
  }
  
  /**
   * To open in a new window, must be done using window.open(). The angular [routerLink] (in .html) always opens in the same browser window
   */
  openDashboard(periodId: number, periodVersionId: number): void {
    const url = this.router.serializeUrl(
      this.router.createUrlTree(['/dashboard', 'EMISSIONS', periodId, periodVersionId])
    );
    window.open(url, '_blank');
  }

  showLogs(): void {
    const modalRef = this.modalService.open(ResilientLogLogsDialogComponent, { size: 'lg', backdrop: 'static' });
    modalRef.componentInstance.ownerId = this.period()?.id;
  }
}
