import App from '../app'
import MenuItem from './menu-item'
import MenuItemRes from './menu-item-res'

export default class Menu {
    constructor(items = []) {
        this.items = items.map(data => new MenuItem(data))
        this.lastHoveredItem = null
    }

    add(item) {
        this.items.push(item)
    }

    addLabel(text, x, y, size = 28) {
        const item = new MenuItem({
            text, x, y, size, type: 'label'
        })

        this.add(item)
    }

    addLabelWithIcon(text, icon, x, y, size = 28) {
        const item = new MenuItem({
            text, icon, x, y, size,
            type: 'label', align: 'left'
        })

        this.add(item)
    }

    addResources(items, x, y) {
        const resources = items.map(item => App.Helpers.makeResourceItem(item.type, item.amount))
        const item = new MenuItemRes({
            resources, x, y
        })

        this.add(item)
    }

    draw(ctx) {
        this.items.forEach(item => item.draw(ctx, this.lastHoveredItem == item))
    }

    mouse(x, y) {
        const activeItems = this.items.filter(item => item.type === 'button' && !item.isDisabled())
        const menuUnderCursor = activeItems.find(item => item.isUnderCursor(x, y))

        if (this.lastHoveredItem !== menuUnderCursor) {
            this.lastHoveredItem = menuUnderCursor
        }
    }

    getHovered() {
        return this.lastHoveredItem
    }
}
