/*
 *   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.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.EntityType;
import org.bukkit.scheduler.BukkitTask;

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 HellsBells {

    public static final Random random = new Random();

    private final int xLength = Config.BlueExtendRegion.getSizeX();
    private final int zLength = Config.BlueExtendRegion.getSizeZ();
    private State current = State.PRE;
    private int currentDrops = 0;
    private HellsBellsCountdown currentCountdown;
    private BukkitTask currentDropping;

    private final List<String> startMessages = Arrays.asList("HELLS_BELLS_START_1", "HELLS_BELLS_START_2",
            "HELLS_BELLS_START_3", "HELLS_BELLS_START_4", "HELLS_BELLS_START_5", "HELLS_BELLS_START_6");
    private final List<String> stateSwapMessages = Arrays.asList("HELLS_BELLS_SWAP_1", "HELLS_BELLS_SWAP_2",
            "HELLS_BELLS_SWAP_3", "HELLS_BELLS_SWAP_4");

    public void startCountdown() {
        if (current == HellsBells.State.PRE || current == HellsBells.State.FIRST) {
            String startMessage = startMessages.get(random.nextInt(startMessages.size()));
            GlobalRecorder.getInstance().system(startMessage);
            FightSystem.getMessage().broadcast(startMessage);
            current = current.getNext();
        } else if (current != HellsBells.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 HellsBellsCountdown(current.MIN_TIME + random.nextInt(current.MAX_TIME - current.MIN_TIME));
        currentCountdown.enable();
    }

    public void drop() {
        Direction direction = Direction.getRandom();

        AtomicInteger length = new AtomicInteger(20 + random.nextInt(direction.getLength(zLength, xLength) - 20));
        int width = 5 + random.nextInt(5);
        int xOffset = getStart(direction.getLength(xLength, zLength), direction.getLength(length.get(), width));
        int zOffset = getStart(direction.getLength(zLength, xLength), direction.getLength(width, length.get()));
        int yOffset = getHeightStart();

        Point redStart;
        Point blueStart;

        if (direction.isNorthOrWest()) {
            redStart = new Point(Config.RedExtendRegion.getMaxX() - xOffset, Config.RedExtendRegion.getMaxY() + yOffset, Config.RedExtendRegion.getMaxZ() - zOffset);
            blueStart = new Point(Config.BlueExtendRegion.getMinX() + xOffset, Config.BlueExtendRegion.getMaxY() + yOffset, Config.BlueExtendRegion.getMinZ() + zOffset);
        } else {
            redStart = new Point(Config.RedExtendRegion.getMinX() + xOffset, Config.RedExtendRegion.getMaxY() + yOffset, Config.RedExtendRegion.getMinZ() + zOffset);
            blueStart = new Point(Config.BlueExtendRegion.getMaxX() - xOffset, Config.BlueExtendRegion.getMaxY() + yOffset, Config.BlueExtendRegion.getMaxZ() - zOffset);
        }

        currentDropping = Bukkit.getScheduler().runTaskTimer(FightSystem.getPlugin(), () -> {
            for (int w = 0; w < width; w++) {
                if (direction.isNorthOrWest()) {
                    Config.world.spawnEntity(redStart.addAndToLocation(Config.world, -1 * (direction.dx * length.get() + w * direction.other().dx), 0, -1 * (direction.dz * length.get() + w * direction.other().dz)), EntityType.TNT);

                    Config.world.spawnEntity(blueStart.addAndToLocation(Config.world, direction.dx * length.get() + w * direction.other().dx, 0, direction.dz * length.get() + w * direction.other().dz), EntityType.TNT);
                } else {
                    Config.world.spawnEntity(redStart.addAndToLocation(Config.world, direction.dx * length.get() + w * direction.other().dx, 0, direction.dz * length.get() + w * direction.other().dz), EntityType.TNT);

                    Config.world.spawnEntity(blueStart.addAndToLocation(Config.world, -1 * (direction.dx * length.get() + w * direction.other().dx), 0, -1 * (direction.dz * length.get() + w * direction.other().dz)), EntityType.TNT);
                }
            }
            if (length.addAndGet(-2) <= 0) {
                currentDropping.cancel();
            }
        }, 0L, 4L);
    }

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

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

    public HellsBells() {
        new StateDependent(Winconditions.HELLS_BELLS, FightState.Running) {
            @Override
            public void enable() {
                current = State.PRE;
                currentDrops = 0;
                startCountdown();
            }

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

    private class HellsBellsCountdown extends Countdown {

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

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

    private enum State {

        PRE(60, 80, 1),
        FIRST(40, 60, 3),
        SECOND(30, 40, 4),
        THIRD(20, 30, 4),
        FOURTH(10, 20, 5),
        LAST(5, 10, 0);


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

        private final int MIN_TIME; //NOSONAR
        private final int MAX_TIME; //NOSONAR
        private final int SWITCH_AFTER; //NOSONAR


        public 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;
            }
        }
    }

    private enum Direction {
        NORTH(0, 0, 1),
        SOUTH(0, 0, -1),
        EAST(1, 0, 0),
        WEST(-1, 0, 0);


        int dx;
        int dy;
        int dz;

        Direction(int dx, int dy, int dz) {
            this.dx = dx;
            this.dy = dy;
            this.dz = dz;
        }

        public static Direction getRandom() {
            return Direction.values()[random.nextInt(Direction.values().length)];
        }

        Direction other() {
            switch (this) {
                case NORTH:
                    return EAST;
                case SOUTH:
                    return WEST;
                case EAST:
                    return NORTH;
                case WEST:
                    return SOUTH;
                default:
                    return this;
            }
        }

        public int getLength(int length1, int length2) {
            return isNorthOrSouth() ? length1 : length2;
        }

        public boolean isNorthOrSouth() {
            return this == NORTH || this == SOUTH;
        }

        public boolean isNorthOrWest() {
            return this == NORTH || this == WEST;
        }
    }
}