'use strict';

const { sleep } = require('../utils');

const FOOD_ITEMS = [
	'golden_carrot', 'cooked_beef', 'steak', 'cooked_porkchop',
	'cooked_mutton', 'cooked_chicken', 'cooked_salmon', 'cooked_cod',
	'baked_potato', 'bread', 'cooked_rabbit', 'golden_apple',
	'carrot', 'apple', 'sweet_berries', 'melon_slice',
	'dried_kelp', 'potato', 'beetroot', 'cookie',
];

class AutoEat {
	constructor(args) {
		this.bot = args.bot;
		this.threshold = args.threshold || 14;
		this.isEating = false;
		this._checkInterval = null;
		this._onHealthListener = null;
	}

	async init() {
		this.onReadyListen = this.bot.on('onReady', () => {
			this._onHealthListener = () => this._onHealth();
			this.bot.bot.on('health', this._onHealthListener);

			this._checkInterval = setInterval(() => this._onHealth(), 30000);

			console.log(`AutoEat: Active (threshold: ${this.threshold}/20)`);
		});
	}

	unload() {
		if (this._checkInterval) {
			clearInterval(this._checkInterval);
			this._checkInterval = null;
		}
		if (this._onHealthListener && this.bot.isReady) {
			this.bot.bot.removeListener('health', this._onHealthListener);
		}
		this._onHealthListener = null;
		if (this.onReadyListen) this.onReadyListen();
		console.log('AutoEat: Unloaded');
	}

	async _onHealth() {
		if (this.isEating) return;
		if (this.bot.bot.food >= this.threshold) return;

		await this._eat();
	}

	async _eat() {
		this.isEating = true;
		try {
			const food = this._findFood();
			if (!food) {
				console.log('AutoEat: No food in inventory');
				return;
			}

			console.log(`AutoEat: Eating ${food.name} (hunger: ${this.bot.bot.food}/20)`);
			await this.bot.bot.equip(food, 'hand');
			await this.bot.bot.consume();
			console.log(`AutoEat: Done (hunger: ${this.bot.bot.food}/20)`);
		} catch (error) {
			console.error('AutoEat: Error eating:', error.message);
		} finally {
			this.isEating = false;
		}
	}

	_findFood() {
		for (const name of FOOD_ITEMS) {
			const item = this.bot.bot.inventory.items().find(i => i.name === name);
			if (item) return item;
		}
		return null;
	}
}

AutoEat.getStatus = function(instance) {
	return {
		threshold: instance.threshold,
		isEating: instance.isEating,
		hunger: instance.bot.isReady ? instance.bot.bot.food : null,
		foodCount: instance.bot.isReady ?
			instance.bot.bot.inventory.items().filter(i => FOOD_ITEMS.includes(i.name)).reduce((s, i) => s + i.count, 0) : 0,
	};
};

module.exports = AutoEat;
