import { ref } from 'vue'

const categories = ref([])
const searchResults = ref([])
const notesChangeCount = ref(0)

let initialized = false

function setupListeners() {
    if (initialized || typeof window === 'undefined') return
    initialized = true

    window.api.onNoteCreated(() => {
        notesChangeCount.value++
    })

    window.api.onNoteUpdated(() => {
        notesChangeCount.value++
    })

    window.api.onNoteDeleted(() => {
        notesChangeCount.value++
    })
}

export default () => {
    setupListeners()

    /* -------------------------
     Initialization
    --------------------------*/
    async function loadCategories() {
        categories.value = await window.notesAPI.call('getCategories')
    }

    async function loadCategoryNotes(category = null) {
        return await window.notesAPI.call('getCategoryNotes', category)
    }

    async function loadNote(id) {
        return await window.notesAPI.call('getNote', id)
    }

    /* -------------------------
     Create
    --------------------------*/
    async function createNote(metadata, content) {
        const note = await window.notesAPI.call('createNote', metadata, content)
        await loadCategories()
        return note
    }

    /* -------------------------
     Update
    --------------------------*/
    async function updateNoteContent(id, content) {
        const note = await window.notesAPI.call('updateNote', id, content)
        return note
    }

    async function updateNoteMetadata(id, updates) {
        const note = await window.notesAPI.call(
            'updateNoteMetadata',
            id,
            updates,
        )
        await loadCategories()
        return note
    }

    async function updateCategory(category, update) {
        const notes = await loadCategoryNotes(category)

        notes.forEach(async (note) => {
            await updateNoteMetadata(note.id, { category: update })
        })

        await loadCategories()
    }

    /* -------------------------
     Search
    --------------------------*/
    async function search(query) {
        if (!query) {
            searchResults.value = []
            return
        }

        searchResults.value = await window.notesAPI.call('search', query)
    }

    return {
        categories,
        searchResults,
        notesChangeCount,

        loadCategories,
        loadCategoryNotes,
        loadNote,

        createNote,
        updateNoteContent,
        updateNoteMetadata,
        updateCategory,

        search,
    }
}
