import { Injectable } from '@angular/core';
import * as selectors from './task-calendar.selectors';
import * as actions from './task-calendar.actions';
import { Store } from '@ngrx/store';
import { DisplayInfoRequest, DisplayInfoDTO, FileDTO } from '@swagger/eis';
import { first } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';
import { fileToBase64, parseMimeTypeFromBase64String } from '../../../modules/task-calendar/utils';

@Injectable({ providedIn: 'root' })
export class TaskCalendarFacade {
  fetching$ = this.store.select(selectors.selectFetching);

  tasks$ = this.store.select(selectors.selectTasks);

  mappedTasks$ = this.store.select(selectors.selectMappedTasks);

  calendarItems$ = this.store.select(selectors.selectCalendarItems);

  filter$ = this.store.select(selectors.selectFilters);

  minAndMaxDate$ = this.store.select(selectors.selectMinMaxDates);

  constructor(private store: Store<any>) {}

  getTaskById$(id: number) {
    return this.store.select(selectors.selectTaskById, id);
  }

  getTasks() {
    this.store.dispatch(actions.getTasksRequest());
  }

  patchTask(id: number, changes: Partial<DisplayInfoDTO>) {
    this.store.dispatch(actions.patchTask({ taskId: id, changes }));
  }

  async addImageToTask(id: number, file: File) {
    const task = await this.getTaskById$(id).pipe(first()).toPromise();

    if (isNullOrUndefined(task)) {
      throw new Error('Task not found');
    }

    const content = await fileToBase64(file);

    const fileDTO: FileDTO = {
      name: file.name,
      type: file.type,
      mime: parseMimeTypeFromBase64String(content),
      size: file.size,
      subtitle: task.title,
      content,
    };

    this.patchTask(id, { images: [...task.images, { data: fileDTO }] });
  }

  setFilter(filter: DisplayInfoRequest) {
    this.store.dispatch(actions.setFilter({ filter }));
  }

  patchFilter(filter: Partial<DisplayInfoRequest>) {
    this.store.dispatch(actions.patchFilter({ filter }));
  }
}
