import * as mc from '@minecraft/server';

import * as main from '../main';
import * as eventmanager from '../event_manager';

export const EVENTID = 1;

export default class MalfunctionEvent {

	eventID;
	name = "Malfunction";
	description = "text.blocklab_friend_exe:emoticon.malfunction";
	description_choice = main.randInt(1, 2);
	progress = "";
	completeText = "text.blocklab_friend_exe:emoticon.malfunction_complete";
	failed = "text.blocklab_friend_exe:emoticon.malfunction_failed";
	time = main.randInt(15, 20);
	isActive = true;
	complete = false;
	currRepairAmount = 0
	repairAmount = main.randInt(2, 4);

	constructor() {
		this.eventID = EVENTID;
	}

	activate(friend_exe) {
		this.time = main.randInt(15, 20);
		friend_exe.runCommand(`effect @s slowness 15 7 true`);
		this.repairAmount = main.randInt(2, 4);

		this.description = this.description + String(this.description_choice);
		this.progress = `§c${this.currRepairAmount}/${this.repairAmount}`;
		mc.world.sendMessage({
			rawtext: [
				{ translate: this.description },
				{ text: " §c(" },
				{ text: this.progress },
				{ text: "§c)" }
			]
		});
	}

	sparkeCount = main.randInt(3, 6);
	randomSound = main.randInt(3, 4);

	tick(friend_exe, mood, moodStage) {
		if (mood > 9) {
			this.isActive = false;
		} else if (this.time == 0) {
			mc.world.sendMessage({
				rawtext: [
					{ translate: this.failed }
				]
			});
			this.complete = false;
			this.isActive = false;
			if (main.randInt(0, 10) > 2) {
				main.setMoodStage(friend_exe, 40);
				mc.system.runTimeout(() => {
					main.setStage(friend_exe, 1);
				}, 70);
			} else {
				main.setMood(friend_exe, 39);
			}
		}
		this.randomSound--;
		if (this.randomSound <= 0) {
			this.randomSound = main.randInt(2, 4);
			friend_exe.runCommand(`playsound mob.ai-friend.jitter_malfunction @a ~ ~ ~`);
		}
		this.sparkeCount--;
		if (this.sparkeCount <= 0) {
			this.sparkeCount = main.randInt(3, 6);
			friend_exe.runCommand(`particle blocklab_friend_exe:sparkle`);
		}
		this.time--;
		if (this.time == 10 || this.time == 5) {
			main.playTimeclockSound();
		}
	}

	deactivate(friend_exe) {
		this.isActive = false;
	}

	repair(player, friend_exe, mood, moodStage) {
		if (moodStage == 0) {
			this.time += 3;
			mc.system.runTimeout(() => {
				this.currRepairAmount++;
				friend_exe.runCommand(`playsound mob.ai-friend.adjust @a ~ ~ ~ 2 ${main.randFloat(0.7, 1.1)}`);
				main.PlayEmote("stage0_headspin", 4);
				if (this.repairAmount == this.currRepairAmount) {
					mc.world.sendMessage({
						rawtext: [
							{ translate: this.completeText }
						]
					});
					main.PlayEmoteSound("happy");
					this.complete = true;
					this.isActive = false;
					const newMood = mood + main.randInt(52, 74);
					main.setMood(friend_exe, newMood);
				}
				if (main.randInt(1, 100) <= 5) main.randomJumpscare(friend_exe);

			}, 20);
			if (this.repairAmount >= 0) {
			}
		}
	}

}