import * as monaco from "monaco-editor-core"
import { LANGUAGE_ID } from "../../constants";
import { WorkerAccessor } from "../types";

export default class DiagnosticsAdapter {

  constructor(private worker: WorkerAccessor) {
    const modelAdd = (model: monaco.editor.IModel) => {
      let handle: NodeJS.Timeout | null = null;

      model.onDidChangeContent(() => {
        if (handle) {
          clearTimeout(handle);
        }
        handle = setTimeout(() => {
          this.validate(model.uri);
        }, 500);
      })

      this.validate(model.uri);
    }
    monaco.editor.onDidCreateModel(modelAdd);

    monaco.editor.getModels().forEach(modelAdd);
  }

  private async validate(resource: monaco.Uri) {

    const worker = await this.worker(resource);

    const diagnostics = await worker.doValidation();
    const model = monaco.editor.getModel(resource);

    monaco.editor.setModelMarkers(model!, LANGUAGE_ID, diagnostics);
  }
}
