package de.hessj.environmentex;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Block;
import org.bukkit.block.Jukebox;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ShapelessRecipe;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.components.CustomModelDataComponent;
import org.bukkit.scheduler.BukkitRunnable;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.SoundStop;
import net.kyori.adventure.text.Component;

public class CustomMusicDiscs implements Listener {

    class Song {
        private String title;
        private String artist;
        private int number;
        private String oggFile;

        public Song(String title, String artist, int number, String oggFile) {
            this.title = title;
            this.artist = artist;
            this.number = number;
            this.oggFile = oggFile;
        }

        public String getTitle() {
            return title;
        }

        public String getArtist() {
            return artist;
        }

        public int getNo() {
            return number;
        }

        public String getOGGPath() {
            return oggFile;
        }
    }

    public String getDiskKey(int customModelData, CustomModelDataComponent cmdc) {
        String key = "custom.";
        key += cmdc.getStrings().get(1);
        return key;
    }

    public void createDiscs(App app) {
        List<Song> songList = new ArrayList<>();

        songList.add(new Song("Stairway to Heaven", "Led Zeppelin", 1,"stairway_to_heaven"));
        songList.add(new Song("M@GICAL☆CURE! LOVE ♥ SHOT!", "Hatsune Miku", 2, "magical_cure_love_shot"));
        songList.add(new Song("Aishiteru Banzai!", "LoveLive!", 3, "aishiteru_banzai"));
        songList.add(new Song("Miku", "Anamanaguchi", 4, "miku"));
        songList.add(new Song("Melt", "Hatsune Miku", 5, "melt"));
        songList.add(new Song("Wurzelheim", "Gamefreak", 6, "littleroot_town"));
        songList.add(new Song("Lavandia", "Gamefreak", 7, "lavandia"));
        songList.add(new Song("Neuborkia", "Gamefreak", 8, "neuborkia"));

        for (Song song : songList) {
            ItemStack customDisc = new ItemStack(Material.MUSIC_DISC_13);
            ItemMeta meta = customDisc.getItemMeta();
            if (meta != null) {
                meta.setCustomModelData(12345);
                meta.displayName(Component.text("§6" + song.artist + " - " + song.title));
                CustomModelDataComponent cmdc = meta.getCustomModelDataComponent();
                List<String> list = Arrays.asList("custom_music_disc", song.getOGGPath());
                cmdc.setStrings(list);
                meta.setCustomModelDataComponent(cmdc);
                customDisc.setItemMeta(meta);
            }

            NamespacedKey nskDisc = new NamespacedKey(app, "custom_music_disc" + song.number);
            ShapelessRecipe reciped = new ShapelessRecipe(nskDisc, customDisc);
            reciped.addIngredient(1, Material.DIAMOND);
            reciped.addIngredient(1, Material.PAPER);
            Bukkit.addRecipe(reciped);
            App.main.recipeKeys.add(reciped.getKey());
        }
    }

    @EventHandler
    public void onJukeboxInsert(PlayerInteractEvent event) {
        if (event.getClickedBlock() != null && event.getClickedBlock().getType() == Material.JUKEBOX) {
            if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
                return;
            }
            Jukebox jukebox = (Jukebox) event.getClickedBlock().getState();
            ItemStack disc = event.getItem();

            if (!jukebox.isPlaying()) {

                if (disc == null || !disc.hasItemMeta()) {
                    return;
                }

                final String k2 = getDiskKey(disc.getItemMeta().getCustomModelData(),
                        disc.getItemMeta().getCustomModelDataComponent());
                event.setCancelled(true);

                new BukkitRunnable() {
                    @Override
                    public void run() {
                        jukebox.setRecord(disc);
                        jukebox.update();

                        if (event.getPlayer().getInventory().getItemInMainHand().equals(disc)) {
                            event.getPlayer().getInventory().setItemInMainHand(null);
                        } else if (event.getPlayer().getInventory().getItemInOffHand().equals(disc)) {
                            event.getPlayer().getInventory().setItemInOffHand(null);
                        }
                        event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), k2,
                                org.bukkit.SoundCategory.RECORDS, 1F, 1f);
                    }

                }.runTaskLater(App.main, 1L);

            } else {
                if (!jukebox.getRecord().hasItemMeta()) {
                    return;
                }

                String key = getDiskKey(jukebox.getRecord().getItemMeta().getCustomModelData(),
                        jukebox.getRecord().getItemMeta().getCustomModelDataComponent());
                event.getPlayer().stopSound(SoundStop.named(Key.key(key)));
            }
        }
    }

    @EventHandler
    public void onJukeboxBreak(BlockBreakEvent event) {
        if (event.getBlock().getType() != Material.JUKEBOX) {
            return;
        }
        Jukebox jukebox = (Jukebox) event.getBlock().getState();

        if (!jukebox.hasRecord() || !jukebox.getRecord().hasItemMeta()) {
            return;
        }

        String key = getDiskKey(jukebox.getRecord().getItemMeta().getCustomModelData(),
                jukebox.getRecord().getItemMeta().getCustomModelDataComponent());
        event.getPlayer().stopSound(SoundStop.named(Key.key(key)));
    }

    @EventHandler
    public void onRedstonePower(BlockRedstoneEvent event) {
        Block block = event.getBlock();

        if (block == null || getNearbyJukebox(block) == null) {
            return;
        }

        Jukebox jukebox = (Jukebox) (block.getType() == Material.JUKEBOX ? block.getState()
                : getNearbyJukebox(block).getState());

        if (event.getNewCurrent() > 0) {
            if (!jukebox.isPlaying() && jukebox.hasRecord()) {

                if (jukebox.getRecord().hasItemMeta()) {
                    String key = getDiskKey(jukebox.getRecord().getItemMeta().getCustomModelData(),
                            jukebox.getRecord().getItemMeta().getCustomModelDataComponent());
                    jukebox.getWorld().playSound(jukebox.getLocation(), key,
                            org.bukkit.SoundCategory.RECORDS, 1F, 1f);

                }
                jukebox.startPlaying();

            } else if (jukebox.isPlaying() && jukebox.hasRecord()) {
                if (jukebox.getRecord().hasItemMeta()) {
                    String key = getDiskKey(jukebox.getRecord().getItemMeta().getCustomModelData(),
                            jukebox.getRecord().getItemMeta().getCustomModelDataComponent());
                    jukebox.getWorld().stopSound(SoundStop.named(Key.key(key)));
                }

                jukebox.stopPlaying();

            }
        }
    }

    private Block getNearbyJukebox(Block block) {
        Block[] distantNeighbors = {
                block.getRelative(2, 0, 0),
                block.getRelative(-2, 0, 0),
                block.getRelative(0, 0, 2),
                block.getRelative(0, 0, -2),
                block.getRelative(0, 2, 0),
                block.getRelative(0, -2, 0)
        };

        for (Block neighbor : distantNeighbors) {
            if (neighbor.getType() == Material.JUKEBOX) {
                Block between = block.getRelative((neighbor.getX() - block.getX()) / 2,
                        (neighbor.getY() - block.getY()) / 2, (neighbor.getZ() - block.getZ()) / 2);
                if (between.getType() == Material.AIR) {
                    return neighbor;
                }
            }
        }
        return null;
    }

}
