/*
 * Decompiled with CFR 0.152.
 * 
 * Could not load the following classes:
 *  com.google.gson.JsonObject
 *  com.google.gson.JsonParser
 *  meteordevelopment.orbit.EventHandler
 *  net.minecraft.class_1011
 *  net.minecraft.class_1043
 *  net.minecraft.class_1044
 *  net.minecraft.class_10799
 *  net.minecraft.class_2960
 *  net.minecraft.class_332
 */
package meteordevelopment.meteorclient.systems.modules.render;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.awt.Color;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import meteordevelopment.meteorclient.events.meteor.MouseClickEvent;
import meteordevelopment.meteorclient.events.render.Render2DEvent;
import meteordevelopment.meteorclient.events.world.TickEvent;
import meteordevelopment.meteorclient.settings.DoubleSetting;
import meteordevelopment.meteorclient.settings.IntSetting;
import meteordevelopment.meteorclient.settings.Setting;
import meteordevelopment.meteorclient.settings.SettingGroup;
import meteordevelopment.meteorclient.settings.StringSetting;
import meteordevelopment.meteorclient.systems.modules.Categories;
import meteordevelopment.meteorclient.systems.modules.Module;
import meteordevelopment.meteorclient.utils.misc.input.KeyAction;
import meteordevelopment.meteorclient.utils.render.RenderUtils;
import meteordevelopment.orbit.EventHandler;
import net.minecraft.class_1011;
import net.minecraft.class_1043;
import net.minecraft.class_1044;
import net.minecraft.class_10799;
import net.minecraft.class_2960;
import net.minecraft.class_332;

public class SpotifyPlayer
extends Module {
    private final SettingGroup sgGeneral;
    private final Setting<Double> xPos;
    private final Setting<Double> yPos;
    private final Setting<String> accessToken;
    private final Setting<Integer> updateInterval;
    private String currentTrack;
    private String currentArtist;
    private long progressMs;
    private long durationMs;
    private boolean isPlaying;
    private String albumArtUrl;
    private String lastAlbumArtUrl;
    private class_2960 albumArtIdentifier;
    private class_1043 albumArtTexture;
    private final ExecutorService executor;
    private int ticks;

    public SpotifyPlayer() {
        super(Categories.Render, "spotify-player", "Shows and controls your Spotify playback.");
        this.sgGeneral = this.settings.getDefaultGroup();
        this.xPos = this.sgGeneral.add(((DoubleSetting.Builder)((DoubleSetting.Builder)new DoubleSetting.Builder().name("x")).description("X position of the player.")).defaultValue(10.0).min(0.0).sliderMax(1920.0).build());
        this.yPos = this.sgGeneral.add(((DoubleSetting.Builder)((DoubleSetting.Builder)new DoubleSetting.Builder().name("y")).description("Y position of the player.")).defaultValue(10.0).min(0.0).sliderMax(1080.0).build());
        this.accessToken = this.sgGeneral.add(((StringSetting.Builder)((StringSetting.Builder)((StringSetting.Builder)new StringSetting.Builder().name("access-token")).description("Your Spotify Access Token.")).defaultValue("")).build());
        this.updateInterval = this.sgGeneral.add(((IntSetting.Builder)((IntSetting.Builder)((IntSetting.Builder)new IntSetting.Builder().name("update-interval")).description("How often to update the song info (in ticks).")).defaultValue(40)).min(20).build());
        this.currentTrack = "Not playing";
        this.currentArtist = "";
        this.progressMs = 0L;
        this.durationMs = 0L;
        this.isPlaying = false;
        this.albumArtUrl = "";
        this.lastAlbumArtUrl = "";
        this.albumArtIdentifier = null;
        this.albumArtTexture = null;
        this.executor = Executors.newSingleThreadExecutor();
        this.ticks = 0;
    }

    @Override
    public void onDeactivate() {
        if (this.albumArtTexture != null) {
            this.albumArtTexture.close();
            this.albumArtTexture = null;
        }
        this.albumArtIdentifier = null;
    }

    @EventHandler
    private void onTick(TickEvent.Post event) {
        ++this.ticks;
        if (this.ticks >= this.updateInterval.get()) {
            this.ticks = 0;
            this.updateSpotify();
        }
        if (this.isPlaying) {
            this.progressMs += 50L;
            if (this.progressMs > this.durationMs) {
                this.progressMs = this.durationMs;
            }
        }
    }

    private void updateSpotify() {
        String token = this.accessToken.get();
        if (token.isEmpty()) {
            return;
        }
        this.executor.execute(() -> {
            try {
                HttpURLConnection conn = (HttpURLConnection)new URL("https://api.spotify.com/v1/me/player/currently-playing").openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Authorization", "Bearer " + token);
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);
                if (conn.getResponseCode() == 200) {
                    InputStream in = conn.getInputStream();
                    String json = new String(in.readAllBytes(), StandardCharsets.UTF_8);
                    JsonObject root = JsonParser.parseString((String)json).getAsJsonObject();
                    if (root.has("item") && !root.get("item").isJsonNull()) {
                        JsonObject item = root.getAsJsonObject("item");
                        this.currentTrack = item.get("name").getAsString();
                        this.currentArtist = item.getAsJsonArray("artists").get(0).getAsJsonObject().get("name").getAsString();
                        this.durationMs = item.get("duration_ms").getAsLong();
                        this.progressMs = root.get("progress_ms").getAsLong();
                        this.isPlaying = root.get("is_playing").getAsBoolean();
                        this.albumArtUrl = item.getAsJsonObject("album").getAsJsonArray("images").get(0).getAsJsonObject().get("url").getAsString();
                        if (!this.albumArtUrl.equals(this.lastAlbumArtUrl)) {
                            this.loadAlbumArt(this.albumArtUrl);
                            this.lastAlbumArtUrl = this.albumArtUrl;
                        }
                    }
                } else if (conn.getResponseCode() == 204) {
                    this.currentTrack = "Not playing";
                    this.currentArtist = "";
                    this.isPlaying = false;
                }
            }
            catch (Exception exception) {
                // empty catch block
            }
        });
    }

    private void loadAlbumArt(String url) {
        this.executor.execute(() -> {
            try {
                InputStream in = new URL(url).openStream();
                class_1011 image = class_1011.method_4309((InputStream)in);
                this.mc.execute(() -> {
                    if (this.albumArtTexture != null) {
                        this.albumArtTexture.close();
                    }
                    this.albumArtTexture = new class_1043(null, image);
                    this.albumArtIdentifier = class_2960.method_60655((String)"meteor-client", (String)"spotify_album_art");
                    this.mc.method_1531().method_4616(this.albumArtIdentifier, (class_1044)this.albumArtTexture);
                });
            }
            catch (Exception exception) {
                // empty catch block
            }
        });
    }

    @EventHandler
    private void onMouseButton(MouseClickEvent event) {
        if (event.action != KeyAction.Press || event.button() != 0) {
            return;
        }
        if (this.mc.field_1755 != null) {
            return;
        }
        double mx = event.click.comp_4798();
        double my = event.click.comp_4799();
        double x = this.xPos.get();
        double y = this.yPos.get();
        int width = 240;
        int height = 80;
        if (mx >= x && mx <= x + (double)width && my >= y && my <= y + (double)height) {
            int textX = (int)x + 80;
            int barWidth = width - 90;
            int centerX = textX + barWidth / 2;
            int centerY = (int)y + 65;
            if (my >= (double)(centerY - 10) && my <= (double)(centerY + 10)) {
                if (mx >= (double)(centerX - 30) && mx <= (double)(centerX - 10)) {
                    this.spotifyAction("previous");
                } else if (mx >= (double)(centerX - 10) && mx <= (double)(centerX + 10)) {
                    this.spotifyAction(this.isPlaying ? "pause" : "play");
                } else if (mx >= (double)(centerX + 10) && mx <= (double)(centerX + 30)) {
                    this.spotifyAction("next");
                }
            }
            event.cancel();
        }
    }

    private void spotifyAction(String action) {
        String token = this.accessToken.get();
        if (token.isEmpty()) {
            return;
        }
        this.executor.execute(() -> {
            try {
                String method;
                String string = method = action.equals("play") || action.equals("pause") || action.equals("next") || action.equals("previous") ? "PUT" : "POST";
                if (action.equals("next") || action.equals("previous")) {
                    method = "POST";
                }
                URL url = new URL("https://api.spotify.com/v1/me/player/" + action);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setRequestMethod(method);
                conn.setRequestProperty("Authorization", "Bearer " + token);
                conn.setConnectTimeout(5000);
                if (conn.getResponseCode() < 300) {
                    if (action.equals("play")) {
                        this.isPlaying = true;
                    } else if (action.equals("pause")) {
                        this.isPlaying = false;
                    }
                    this.ticks = this.updateInterval.get();
                }
            }
            catch (Exception exception) {
                // empty catch block
            }
        });
    }

    @EventHandler
    private void onRender2D(Render2DEvent event) {
        if (this.mc.field_1724 == null) {
            return;
        }
        class_332 context = event.drawContext;
        double x = this.xPos.get();
        double y = this.yPos.get();
        int width = 240;
        int height = 80;
        Color bg = new Color(20, 20, 20, 200);
        RenderUtils.renderRoundedQuad(context.method_51448(), bg, x, y, x + (double)width, y + (double)height, 6.0, 20.0);
        if (this.albumArtIdentifier != null) {
            context.method_25290(class_10799.field_56883, this.albumArtIdentifier, (int)x + 8, (int)y + 8, 0.0f, 0.0f, 64, 64, 64, 64);
        } else {
            context.method_25294((int)x + 8, (int)y + 8, (int)x + 72, (int)y + 72, -13421773);
        }
        int textX = (int)x + 80;
        Object track = this.currentTrack;
        if (((String)track).length() > 20) {
            track = ((String)track).substring(0, 18) + "...";
        }
        context.method_51433(this.mc.field_1772, (String)track, textX, (int)y + 12, -1, false);
        Object artist = this.currentArtist;
        if (((String)artist).length() > 25) {
            artist = ((String)artist).substring(0, 23) + "...";
        }
        context.method_51433(this.mc.field_1772, (String)artist, textX, (int)y + 24, -5592406, false);
        int barWidth = width - 90;
        int barX = textX;
        int barY = (int)y + 42;
        context.method_25294(barX, barY, barX + barWidth, barY + 3, -12303292);
        if (this.durationMs > 0L) {
            int progressWidth = (int)((double)barWidth * ((double)this.progressMs / (double)this.durationMs));
            context.method_25294(barX, barY, barX + progressWidth, barY + 3, -14829228);
        }
        String time = this.formatTime(this.progressMs) + " / " + this.formatTime(this.durationMs);
        context.method_51433(this.mc.field_1772, time, barX, barY + 8, -5592406, false);
        String controls = " \u23ee  " + (this.isPlaying ? "\u23f8" : "\u25b6") + "  \u23ed";
        context.method_51433(this.mc.field_1772, controls, barX + barWidth / 2 - this.mc.field_1772.method_1727(controls) / 2, (int)y + 62, -1, false);
    }

    private String formatTime(long ms) {
        long s = ms / 1000L;
        long m = s / 60L;
        return String.format("%d:%02d", m, s %= 60L);
    }
}

