import './entity/chicken_breeder.js'
import './entity/chicken_nest.js'
import './entity/egg_processor.js'
import './entity/egg_collector.js'
import './item/capture_net.js'
import './item/egg.js'
import { world } from '@minecraft/server'

import { nextPage, previousPage, removeIntroductionBook, searchPage, spawnIntroductionBook } from './introduction_book.js'

function spawnBook(player) {
    player.runCommand('function ds/mch/spawn_book')
    player.addTag('ds_mch:received_book')
}

world.afterEvents.playerSpawn.subscribe((event) => {
    const { initialSpawn, player } = event

    if (!initialSpawn) return
    if (player.hasTag('ds_mch:received_book')) return

    spawnBook(player)
})

world.afterEvents.itemUse.subscribe((event) => {
    const { itemStack, source } = event

    if (source.typeId != 'minecraft:player') return

    if (itemStack.typeId === 'ds_mch:introduction_book_item') {
        spawnIntroductionBook(source)
        return
    }
})

world.afterEvents.playerInteractWithEntity.subscribe((event) => {
    const { target, player } = event

    switch (target.typeId) {
        case 'ds_mch:left_page':
            previousPage(target)
            break
        case 'ds_mch:right_page':
            nextPage(target)
            break
        case 'ds_mch:search_button':
            searchPage(target, player)
            break
    }
})

world.afterEvents.entityHitEntity.subscribe((event) => {
    const { damagingEntity, hitEntity } = event

    if (damagingEntity.typeId != 'minecraft:player') return

    switch (hitEntity.typeId) {
        case 'ds_mch:introduction_book':
        case 'ds_mch:left_page':
        case 'ds_mch:right_page':
        case 'ds_mch:search_button':
            removeIntroductionBook(hitEntity)
            break
    }
})