import { ChangeDetectionStrategy, ChangeDetectorRef, Component, input, OnInit, output, ViewChild, ViewEncapsulation } from '@angular/core';
import { BehaviorSubject, catchError, filter, Observable, retry, shareReplay, Subject, switchMap, tap } from 'rxjs';
import { NotifyService } from '../../_shared/services/notify.service';
import { DialogService } from '@progress/kendo-angular-dialog';
import { CustomFormBuilder } from '../../_shared/services/custom-form-builder.service';
import { MessageService } from '../../_shared/services/message.service';
import { HistoryResponse, SosSnapshot, SosSnapshotHistoryService } from './sos-snapshot-history.service';
import { CommonModule } from '@angular/common';
import { GridComponent, GridModule } from '@progress/kendo-angular-grid';
import { TooltipDirective } from '@progress/kendo-angular-tooltip';
import * as util from '../../_shared/utils/util';
import { FAST_KENDO_COMMON, FAST_PAGE_COMMON } from '../../app.config';
import { SortDescriptor } from '@progress/kendo-data-query';

interface fileNameInfo {
  fileNameOnDisk: string;
  fileNameOriginal: string;
}

@Component({
  selector: 'app-sos-snapshot-history',
  standalone: true,
  imports: [FAST_KENDO_COMMON, FAST_PAGE_COMMON, CommonModule, GridComponent, GridModule],
  templateUrl: './sos-snapshot-history.component.html',
  styleUrl: './sos-snapshot-history.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None
})
export class SosSnapshotHistoryComponent implements OnInit {
  @ViewChild('tooltipGrid') tooltipGrid: TooltipDirective;

  util = util;
  icons = util.icons;
  snapshotHistoryResult$: Observable<HistoryResponse>;
  snapshotHistory$ = new BehaviorSubject<void>(undefined);
  snapshotHistoryLoading$ = new BehaviorSubject<boolean>(false);
  closeSnapshotHistory = output();
  downloadSnapshot$ = new Subject<fileNameInfo>();
  pipeId = input.required<number>();
  deliveryPointId = input.required<number>();
  nomDate = input.required<Date>();
  pipeName: string = '';
  pointName: string = '';
  gridSort: SortDescriptor[] = [{ field: 'createdTime', dir: 'desc' }];

  constructor(private messageService: MessageService, private service: SosSnapshotHistoryService, private fb: CustomFormBuilder, private ref: ChangeDetectorRef, private dialogService: DialogService, private notify: NotifyService,) {

    this.snapshotHistoryResult$ = this.snapshotHistory$.pipe(
      tap(() => {
        this.snapshotHistoryLoading$.next(true);
      }),
      switchMap(() => {
        return this.service.getSnapshotHistory(this.pipeId(), this.deliveryPointId(), this.nomDate());
      }),
      tap((response) => {
        this.pipeName = response.nameInfo.pipeName;
        this.pointName = response.nameInfo.deliveryPointName;
        response.snapshots.forEach((snapshot) => {
          snapshot.createdTime = new Date(snapshot.createdTime);
        });
        this.snapshotHistoryLoading$.next(false);
      }),
      shareReplay(1),
      catchError((err) => {
        throw err;
      }),
      retry(3)
    );
  }

  ngOnInit(): void {
    this.snapshotHistory$.next();
  }

  downloadSnapshot(snapshot: SosSnapshot) {
    const fileNameOnDisk = snapshot.fileNameOnDisk;
    const fileNameOriginal = snapshot.fileNameOriginal;
    this.downloadSnapshot$.next({ fileNameOnDisk, fileNameOriginal });
  }

  closedClicked(): void {
    this.closeSnapshotHistory.emit();
  }

  downloadSnapshotResult$ = this.downloadSnapshot$.pipe(
    filter(fileNameInfo => {
      return fileNameInfo && fileNameInfo.fileNameOnDisk !== null && fileNameInfo.fileNameOriginal !== null;
    }),
    switchMap(fileNameInfo => {
      return this.service.downloadSnapshot(fileNameInfo.fileNameOnDisk, fileNameInfo.fileNameOriginal);
    }),
    tap(res => {
      util.openOrSaveFile(res.fileBlob, res.fileName);
    }),
    catchError(err => {
      return util.handleError(err, this.messageService);
    }), retry(10)
  )
}

