import { ChangeDetectionStrategy, Component } from '@angular/core';
import { DomainTaskCalendarService } from '@domain/task-calendar';
import { UiErrorModalComponent, UiModalRef, UiModalService } from '@ui/modal';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'camera-capture-modal',
  templateUrl: 'camera-capture-modal.component.html',
  styleUrls: ['camera-capture-modal.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CameraCaptureModalComponent {
  loading$ = new BehaviorSubject<boolean>(false);
  infoId: number;
  image: string;

  constructor(
    private _modalRef: UiModalRef<string, { image: string; infoId: number }>,
    private _domainTaskCalendarService: DomainTaskCalendarService,
    private _uiModal: UiModalService
  ) {
    this.image = this._modalRef.data.image;
    this.infoId = this._modalRef.data.infoId;
  }

  close() {
    this._modalRef.close();
  }

  repeat() {
    this._modalRef.close('');
  }

  async send() {
    this.loading$.next(true);

    try {
      // TODO: Image Compression compressor.js
      await this._domainTaskCalendarService.complete({ infoId: this.infoId, file: this.image }).toPromise();
    } catch (err) {
      this._uiModal.open({ content: UiErrorModalComponent, data: err, title: 'Fehler beim Hochladen' });
    }

    this._modalRef.close(this.image);
    this.loading$.next(false);
  }
}
