/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.fightsystem.event;

import de.steamwar.fightsystem.Config;
import de.steamwar.fightsystem.FightSystem;
import de.steamwar.fightsystem.countdown.Countdown;
import de.steamwar.fightsystem.record.GlobalRecorder;
import de.steamwar.fightsystem.states.FightState;
import de.steamwar.fightsystem.states.StateDependent;
import de.steamwar.fightsystem.states.StateDependentListener;
import de.steamwar.fightsystem.utils.Message;
import de.steamwar.fightsystem.utils.SWSound;
import de.steamwar.fightsystem.winconditions.Winconditions;
import de.steamwar.linkage.Linked;
import org.bukkit.Bukkit;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.LargeFireball;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;

@Linked
public class Meteor implements Listener {

	public static final Random random = new Random();

	private final Vector vector = new Vector(0, -1, 0);
	private final int xLength = Config.RedExtendRegion.getMaxX() - Config.RedExtendRegion.getMinX();
	private final int zLength = Config.RedExtendRegion.getMaxZ() - Config.RedExtendRegion.getMinZ();
	private Meteor.State current = Meteor.State.PRE;
	private int currentDrops = 0;
	private Meteor.MeteorCountdown currentCountdown;
	private final AtomicInteger amount = new AtomicInteger(0);
	private BukkitTask currentDropping;

	private final List<String> startMessages = Arrays.asList("METEOR_START_1", "METEOR_START_2", "METEOR_START_3", "METEOR_START_4", "METEOR_START_5", "METEOR_START_6");
	private final List<String> stateSwapMessages = Arrays.asList("METEOR_SWAP_1", "METEOR_SWAP_2", "METEOR_SWAP_3", "METEOR_SWAP_4");

	public void startCountdown() {
		if (current == Meteor.State.PRE || current == Meteor.State.FIRST) {
			String startMessage = startMessages.get(random.nextInt(startMessages.size()));
			GlobalRecorder.getInstance().system(startMessage);
			FightSystem.getMessage().broadcast(startMessage);
			current = current.getNext();
		} else if (current != Meteor.State.LAST && currentDrops >= current.SWITCH_AFTER) {
			String stateSwapMessage = stateSwapMessages.get(random.nextInt(stateSwapMessages.size()));
			GlobalRecorder.getInstance().system(stateSwapMessage);
			FightSystem.getMessage().broadcast(stateSwapMessage);
			currentDrops = 0;
			current = current.getNext();
		}

		currentDrops++;
		currentCountdown = new Meteor.MeteorCountdown(current.MIN_TIME + random.nextInt(current.MAX_TIME - current.MIN_TIME));
		currentCountdown.enable();
	}

	//@EventHandler
	public void explode(ProjectileHitEvent event) {
		if (event.getEntity() instanceof Fireball) {
			TNTPrimed tnt = Config.world.spawn(event.getEntity().getLocation(), TNTPrimed.class);
			tnt.setVelocity(new Vector(0, 0, 0));
			tnt.setFuseTicks(0);
			tnt.setYield(((Fireball) event.getEntity()).getYield());
			event.getEntity().remove();
		}
	}

	public void drop() {
		int randomAmount = current.minAmount + random.nextInt(current.maxAmount - current.minAmount);
		if (amount.get() > 0) {
			amount.set(amount.get() + randomAmount);
			return;
		}
		amount.set(randomAmount);

		currentDropping = Bukkit.getScheduler().runTaskTimer(FightSystem.getPlugin(), () -> {
			int xOffset = getStart(xLength);
			int zOffset = getStart(zLength);
			int yOffset = getHeightStart();

			Point redStart = new Point(Config.RedExtendRegion.getMinX() + xOffset, Config.RedExtendRegion.getMaxY() + yOffset, Config.RedExtendRegion.getMaxZ() - zOffset);
			Point blueStart = new Point(Config.BlueExtendRegion.getMinX() + xOffset, Config.BlueExtendRegion.getMaxY() + yOffset, Config.BlueExtendRegion.getMinZ() + zOffset);

			vector.setX(random.nextDouble() - 0.5);
			vector.setZ(random.nextDouble() - 0.5);

			LargeFireball fireballRed = Config.world.spawn(redStart.toLocation(Config.world), LargeFireball.class);
			fireballRed.setDirection(vector);
			fireballRed.setBounce(false);
			fireballRed.setIsIncendiary(false);
			fireballRed.setYield(current.explosionSize);

			LargeFireball fireballBlue = Config.world.spawn(blueStart.toLocation(Config.world), LargeFireball.class);
			vector.setZ(vector.getZ() * -1);
			fireballBlue.setDirection(vector);
			fireballBlue.setBounce(false);
			fireballBlue.setIsIncendiary(false);
			fireballBlue.setYield(current.explosionSize);

			if (amount.decrementAndGet() <= 0) {
				currentDropping.cancel();
			}
		}, 0L, 4L);
	}

	private int getStart(int regionSize) {
		double randomNumber = (random.nextDouble() - random.nextDouble()) / 2 + 0.5;
		Bukkit.getLogger().log(Level.INFO, "Calculated Start: " + (int) (randomNumber * (regionSize - 1)));
		return Math.max(Math.min((int) (randomNumber * (regionSize - 1)), regionSize - 1), 0);
	}

	private int getHeightStart() {
		return 5 + random.nextInt(15);
	}

	public Meteor() {
		new StateDependentListener(Winconditions.METEOR, FightState.Running, this);

		new StateDependent(Winconditions.METEOR, FightState.Running) {
			@Override
			public void enable() {
				startCountdown();
			}

			@Override
			public void disable() {
				currentCountdown.disable();
			}
		}.register();
	}

	private class MeteorCountdown extends Countdown {

		public MeteorCountdown(int time) {
			super(time, new Message("METEOR_COUNTDOWN"), SWSound.BLOCK_NOTE_BASS, true);
		}

		@Override
		public void countdownFinished() {
			drop();
			startCountdown();
		}
	}

	private enum State {

		PRE(60, 80, 1, 0, 0, 0),
		FIRST(25, 35, 6, 2, 3, 6),
		SECOND(20, 30, 7, 4, 4, 8),
		THIRD(15, 25, 7, 4, 5, 10),
		FOURTH(10, 20, 8, 6, 7, 14),
		LAST(5, 10, 0, 6, 9, 18);


		State(int minTime, int maxTime, int switchAfter, int explosionSize, int minAmount, int maxAmount) {
			this.MIN_TIME = minTime;
			this.MAX_TIME = maxTime;
			this.SWITCH_AFTER = switchAfter;
			this.explosionSize = explosionSize;
			this.minAmount = minAmount;
			this.maxAmount = maxAmount;
		}

		private final int MIN_TIME; //NOSONAR
		private final int MAX_TIME; //NOSONAR
		private final int SWITCH_AFTER; //NOSONAR
		private final int explosionSize; //NOSONAR
		private final int minAmount;
		private final int maxAmount;


		public Meteor.State getNext() {
			switch (this) {
				case PRE:
					return FIRST;
				case FIRST:
					return SECOND;
				case SECOND:
					return THIRD;
				case THIRD:
					return FOURTH;
				case FOURTH:
				case LAST:
					return LAST;
				default:
					return PRE;
			}
		}
	}
}