import './style.css';
import './app.css';

import {basicSetup} from "codemirror";
import {EditorView, keymap} from "@codemirror/view";
import {Compartment} from "@codemirror/state";
import {oneDark} from "@codemirror/theme-one-dark";
import {Application} from "@hotwired/stimulus";

import {textProcessor} from "./services.js";
import {multiCursorKeymap, commandPalette} from "./cmplugins.js";
import {indentWithTab} from "@codemirror/commands";

const darkMode = window.matchMedia("(prefers-color-scheme: dark)");
const themeCompartment = new Compartment();

import {StatusController} from "./controllers/status_controller.js";
import {CommandsController} from "./controllers/commands_controller.js";
import {PromptController} from "./controllers/prompt_controller.js";



const view = new EditorView({
    parent: document.querySelector("#app .editor-mountpoint"),
    doc: "",
    extensions: [
        basicSetup,
        keymap.of([indentWithTab]),
        EditorView.lineWrapping,
        multiCursorKeymap,
        commandPalette,
        themeCompartment.of(darkMode.matches ? oneDark : []),
    ]
})

darkMode.addEventListener("change", (e) => {
    view.dispatch({
        effects: themeCompartment.reconfigure(e.matches ? oneDark : []),
    });
});

window.Stimulus = Application.start()
Stimulus.register("commands", CommandsController);
Stimulus.register("prompt", PromptController);
Stimulus.register("status", StatusController);

textProcessor.setCodeMirrorEditor(view);
textProcessor.loadCurrentBuffer().then(() => textProcessor.startAutoSaver());

view.focus();