package zenith.zov.client.modules.impl.misc;

import com.darkmagician6.eventapi.EventManager;
import com.darkmagician6.eventapi.EventTarget;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.resource.Resource;
import net.minecraft.scoreboard.Scoreboard;
import net.minecraft.scoreboard.ScoreboardDisplaySlot;
import net.minecraft.scoreboard.ScoreboardObjective;
import net.minecraft.util.Identifier;
import zenith.zov.base.events.impl.player.EventUpdate;
import zenith.zov.client.modules.api.Category;
import zenith.zov.client.modules.api.Module;
import zenith.zov.client.modules.api.ModuleAnnotation;
import zenith.zov.client.modules.api.setting.impl.BooleanSetting;
import zenith.zov.client.modules.api.setting.impl.NumberSetting;

@ModuleAnnotation(
    name = "ScoreboardChanger",
    description = "Modify scoreboard display",
    category = Category.MISC
)
public class ScoreboardChanger extends Module {
    public static final ScoreboardChanger INSTANCE = new ScoreboardChanger();
    private final BooleanSetting hideScoreboard = new BooleanSetting("Hide Scoreboard", false);
    private final BooleanSetting customTitle = new BooleanSetting("Custom Title", false);
    private final BooleanSetting customScores = new BooleanSetting("Custom Scores", false);
    private final BooleanSetting usePluginConfig = new BooleanSetting("Use Plugin Config", true);
    private final NumberSetting maxScores = new NumberSetting("Max Scores", 7.0F, 1.0F, 15.0F, 1.0F);
    private String titleText = "Example5HP";
    private String moneyValue = "0";
    private String shardsValue = "0";
    private String killsValue = "0";
    private String deathsValue = "0";
    private String keyallValue = "59m 56s";
    private String playtimeValue = "5s";
    private String teamInfo = "Europe (25)";
    private final String[] resourcePaths = new String[]{"config/scoreboard.yml", "assets/zenith/config/scoreboard.yml", "assets/zenith/scoreboard.yml"};
    private final String[] configPaths = new String[]{
        "plugins/TAB/config.yml",
        "config/scoreboard.yml",
        "plugins/Scoreboard/config.yml",
        "plugins/AnimatedScoreboard/config.yml",
        "plugins/SimpleScoreboard/config.yml",
        "plugins/ScoreboardPlus/config.yml"
    };
    private Scoreboard originalScoreboard = null;
    private ScoreboardObjective originalObjective = null;

    public ScoreboardChanger() {
        EventManager.register(this);
    }

    @EventTarget
    public void onUpdate(EventUpdate event) {
        if (mc.player != null && mc.world != null) {
            if (this.isEnabled()) {
                if (this.usePluginConfig.isEnabled()) {
                    this.loadPluginConfig();
                }

                if (this.hideScoreboard.isEnabled()) {
                    this.hideScoreboard();
                } else if (this.customTitle.isEnabled() || this.customScores.isEnabled()) {
                    this.modifyScoreboard();
                }
            } else {
                this.restoreScoreboard();
            }
        }
    }

    private void hideScoreboard() {
    }

    public boolean isHideScoreboard() {
        return this.hideScoreboard.isEnabled();
    }

    public boolean isCustomTitle() {
        return this.customTitle.isEnabled();
    }

    public boolean isCustomScores() {
        return this.customScores.isEnabled();
    }

    public String getTitleText() {
        return this.titleText;
    }

    public String getMoneyValue() {
        return this.moneyValue;
    }

    public String getShardsValue() {
        return this.shardsValue;
    }

    public String getKillsValue() {
        return this.killsValue;
    }

    public String getDeathsValue() {
        return this.deathsValue;
    }

    public String getKeyallValue() {
        return this.keyallValue;
    }

    public String getPlaytimeValue() {
        return this.playtimeValue;
    }

    public String getTeamInfo() {
        return this.teamInfo;
    }

    private void modifyScoreboard() {
        if (mc.world != null && mc.world.getScoreboard() != null) {
            Scoreboard scoreboard = mc.world.getScoreboard();
            ScoreboardObjective objective = scoreboard.getObjectiveForSlot(ScoreboardDisplaySlot.SIDEBAR);
            if (objective != null) {
                if (this.originalScoreboard == null) {
                    this.originalScoreboard = scoreboard;
                    this.originalObjective = objective;
                }

                if (this.customTitle.isEnabled()) {
                    this.loadPluginConfig();
                }

                if (this.customScores.isEnabled()) {
                    this.loadPluginConfig();
                }
            }
        }
    }

    private void restoreScoreboard() {
        this.originalScoreboard = null;
        this.originalObjective = null;
    }

    private void loadPluginConfig() {
        if (!this.loadFromResources()) {
            for (String configPath : this.configPaths) {
                Path path = Paths.get(configPath);
                if (Files.exists(path)) {
                    this.loadConfigFile(path);
                    break;
                }
            }
        }
    }

    private boolean loadFromResources() {
        if (mc.getResourceManager() == null) {
            return false;
        } else {
            for (String resourcePath : this.resourcePaths) {
                try {
                    Identifier identifier = Identifier.of("zenith", resourcePath);
                    Resource resource = (Resource)mc.getResourceManager().getResource(identifier).orElse(null);
                    if (resource != null) {
                        boolean var8;
                        try (InputStream inputStream = resource.getInputStream()) {
                            this.loadConfigFromStream(inputStream, resourcePath);
                            var8 = true;
                        }

                        return var8;
                    }
                } catch (Exception var12) {
                }
            }

            return false;
        }
    }

    private void loadConfigFromStream(InputStream inputStream, String resourcePath) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            List<String> lines = new ArrayList<>();

            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }

            this.parseConfigLines(lines, resourcePath);
        } catch (IOException var8) {
        }
    }

    private void loadConfigFile(Path configPath) {
        try {
            List<String> lines = Files.readAllLines(configPath);
            this.parseConfigLines(lines, configPath.toString());
        } catch (IOException var3) {
        }
    }

    private void parseConfigLines(List<String> lines, String source) {
        boolean inScoreboardSection = false;
        boolean inLinesSection = false;
        int lineIndex = 0;

        for (String line : lines) {
            line = line.trim();
            if (!line.startsWith("#") && !line.isEmpty()) {
                if (line.equals("scoreboard:")) {
                    inScoreboardSection = true;
                } else if (inScoreboardSection && line.equals("lines:")) {
                    inLinesSection = true;
                    lineIndex = 0;
                } else {
                    if (inScoreboardSection && !line.startsWith(" ") && !line.startsWith("-") && line.contains(":")) {
                        inScoreboardSection = false;
                        inLinesSection = false;
                    }

                    if (inLinesSection && line.startsWith("- ")) {
                        String value = line.substring(2).trim();
                        switch (lineIndex) {
                            case 0:
                            case 8:
                            default:
                                break;
                            case 1:
                                if (value.contains("Money") && value.contains("%coinsengine_balance_short_money%")) {
                                    this.moneyValue = "0";
                                }
                                break;
                            case 2:
                                if (value.contains("Shards") && value.contains("%coinsengine_balance_short_shards%")) {
                                    this.shardsValue = "0";
                                }
                                break;
                            case 3:
                                if (value.contains("Kills") && value.contains("%skstatistics_kills%")) {
                                    this.killsValue = "0";
                                }
                                break;
                            case 4:
                                if (value.contains("Deaths") && value.contains("%skstatistics_deaths%")) {
                                    this.deathsValue = "0";
                                }
                                break;
                            case 5:
                                if (value.contains("Keyall") && value.contains("%zschedulers_time_keyall%")) {
                                    this.keyallValue = "59m 56s";
                                }
                                break;
                            case 6:
                                if (value.contains("Playtime") && value.contains("%playtime_timed%")) {
                                    this.playtimeValue = "5s";
                                }
                                break;
                            case 7:
                                if (value.contains("Team") && value.contains("%skteams_name%")) {
                                    this.teamInfo = "Europe (25)";
                                }
                                break;
                            case 9:
                                if (value.contains("Europe") && value.contains("%ping%")) {
                                    this.teamInfo = "Europe (25)";
                                }
                        }

                        lineIndex++;
                    }

                    if (inScoreboardSection && line.startsWith("title:")) {
                        String value = line.substring(6).trim().replace("'", "").replace("\"", "");
                        this.titleText = value;
                    }
                }
            }
        }
    }

    private void savePluginConfig() {
        for (String configPath : this.configPaths) {
            Path path = Paths.get(configPath);
            if (Files.exists(path)) {
                this.saveConfigFile(path);
                break;
            }
        }
    }

    private void saveConfigFile(Path configPath) {
        try {
            List<String> lines = Files.readAllLines(configPath);
            List<String> newLines = new ArrayList<>();

            for (String line : lines) {
                String newLine = line;
                if (line.contains(":")) {
                    String[] parts = line.split(":", 2);
                    if (parts.length == 2) {
                        String key = parts[0].trim();
                        String var9 = key.toLowerCase();
                        switch (var9) {
                            case "title":
                            case "scoreboard.title":
                                newLine = key + ": \"" + this.titleText + "\"";
                                break;
                            case "money":
                            case "scoreboard.money":
                                newLine = key + ": \"" + this.moneyValue + "\"";
                                break;
                            case "shards":
                            case "scoreboard.shards":
                                newLine = key + ": \"" + this.shardsValue + "\"";
                                break;
                            case "kills":
                            case "scoreboard.kills":
                                newLine = key + ": \"" + this.killsValue + "\"";
                                break;
                            case "deaths":
                            case "scoreboard.deaths":
                                newLine = key + ": \"" + this.deathsValue + "\"";
                                break;
                            case "keyall":
                            case "scoreboard.keyall":
                                newLine = key + ": \"" + this.keyallValue + "\"";
                                break;
                            case "playtime":
                            case "scoreboard.playtime":
                                newLine = key + ": \"" + this.playtimeValue + "\"";
                                break;
                            case "team":
                            case "scoreboard.team":
                                newLine = key + ": \"" + this.teamInfo + "\"";
                        }
                    }
                }

                newLines.add(newLine);
            }

            Files.write(configPath, newLines);
        } catch (IOException var11) {
        }
    }
}
