/* 
    This file is a part of the SteamWar software.
    
    Copyright (C) 2020  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.misslewars;

import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;

public class SpawnPlatformCreator {

	private final Player player;
	private final Location spawn;
	private final BukkitTask task;

	private Block currentBlock;
	private int ticks;

	public SpawnPlatformCreator(Player player){
		this.player = player;
		MWTeam team = MissileWars.getTeam(player);
		if(team == null)
			this.spawn = Config.BlueSpawn;
		else
			this.spawn = team.getSpawn();
		ticks = Config.PlatformTime;
		currentBlock = null;
		task = Bukkit.getScheduler().runTaskTimer(MissileWars.getPlugin(), this::createPlatform, 0, 1);
	}

	private void createPlatform(){
		Location playerLoc = player.getLocation();
		playerLoc.setY(spawn.getY() - 1);

		if(currentBlock == null || !currentBlock.getLocation().equals(playerLoc)){
			if(currentBlock != null){
				if(currentBlock.getType() == Material.OBSIDIAN)
					currentBlock.setType(Material.AIR);
				currentBlock = null;
			}

			Block newBlock = playerLoc.getBlock();
			if(newBlock.getType() == Material.AIR){
				newBlock.setType(Material.OBSIDIAN);
				currentBlock = newBlock;
			}
		}

		if(currentBlock != null && player.getLocation().getY() - 1 < currentBlock.getY())
			player.teleport(playerLoc.add(0, 1, 0));

		player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText("Spawnplattform§8: §c§l" + String.format("%.2f", ticks / 20f) + "§8s"));

		if(ticks == 0){
			if(currentBlock != null && currentBlock.getType() == Material.OBSIDIAN)
				currentBlock.setType(Material.AIR);

			task.cancel();
		}
		ticks--;
	}
}
