const bot = require('./bot').get()

async function tossItem(name, amount) {
    amount = parseInt(amount, 10)
    const item = itemByName(name)
    if (!item) {
        bot.chat(`I have no ${name}`)
    } else {
        try {
            if (amount) {
                await bot.toss(item.type, null, amount)
                bot.chat(`tossed ${amount} x ${name}`)
            } else {
                await bot.tossStack(item)
                bot.chat(`tossed ${name}`)
            }
        } catch (err) {
            bot.chat(`unable to toss: ${err.message}`)
        }
    }
}

function itemByName(name) {
    return bot.inventory.items().filter(item => item.name === name)[0]
}

function itemToString(item) {
    if (item) {
        return `${item.name} x ${item.count}`
    } else {
        return '(nothing)'
    }
}

function sayItems(items = bot.inventory.items()) {
    const output = items.map(itemToString).join(', ')
    if (output) {
        bot.chat(output)
    } else {
        bot.chat('empty')
    }
}

module.exports = {
    tossItem: tossItem,
    sayItems: sayItems,
    itemByName: itemByName,
    itemToString: itemToString
}