import { Component, Input,Output, HostListener, ChangeDetectorRef, OnDestroy, OnInit,EventEmitter } from '@angular/core';
import { ResumableFileUploadService, File } from './resumable-file-upload.service';
import { Subscription } from 'rxjs';
import { Store } from '@ngrx/store';
import * as commonReducer from '../../reducers/app-common.reducer';
import * as commonActions from '../../actions/app-common.actions';


@Component({
    selector: 'fm-resumable-file-upload',
    templateUrl: './resumable-file-upload.component.html',
    styleUrls: ['./resumable-file-upload.component.scss'],
    standalone: false
})

export class ResumableFileUploadComponent implements OnInit, OnDestroy {

  @Input('parentCode')
  set parentCode(parentCode: string) {
    if (parentCode && parentCode != "null" && parentCode != "")
      this.uploadService.parentCode = parentCode;
    else
      this.uploadService.parentCode = null;
  }         

    constructor(private cd: ChangeDetectorRef, public uploadService: ResumableFileUploadService,public store: Store<commonReducer.State>) {
    }

    private refreshSub: Subscription;

    ngOnInit() {
      this.uploadService.init();
      this.refreshSub = this.uploadService.refresh.subscribe((e: any) => {
        this.cd.markForCheck();
      });  
    }

    ngOnDestroy() {
      if(this.refreshSub) this.refreshSub.unsubscribe();
    }

    handleUploadedFileClick(event:MouseEvent,file:File) {
      event.preventDefault();
      this.store.dispatch(new commonActions.UploadedFileClick(file.itemCode));
    }

    //TODO do this with an canunload guard
    @HostListener('window:beforeunload')
    windowBeforeUnload = function () {
        if (this.uploadService.isUploading) {
            return false;
        }
    }        
}
