import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { RemissionProcess } from '../models/remission-process';
import { compare } from '../utils/compare';

@Injectable({ providedIn: 'root' })
export class ProcessStoreService {
  private readonly store: Map<number, BehaviorSubject<RemissionProcess>> = new Map();

  constructor() {}

  set(process: RemissionProcess) {
    let processSub: BehaviorSubject<RemissionProcess> = this.get(process.id);

    if (processSub instanceof BehaviorSubject) {
      if (!compare(processSub.value, process)) {
        processSub.next(process);
      }
    } else {
      processSub = new BehaviorSubject(process);
      this.store.set(process.id, processSub);
    }

    return processSub;
  }

  get(processId: number) {
    return this.store.get(processId);
  }

  remove(processId: number) {
    const processSub = this.get(processId);

    if (processSub instanceof BehaviorSubject) {
      processSub.complete();
      this.store.delete(processId);
    }
  }
}
