/*
 *   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.core.authlib;

import com.mojang.authlib.Agent;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.GameProfileRepository;
import com.mojang.authlib.ProfileLookupCallback;
import de.steamwar.Reflection;
import de.steamwar.sql.SteamwarUser;

import java.util.ArrayList;
import java.util.List;

public class SteamwarGameProfileRepository8 extends SteamwarGameProfileRepository {

    private static final GameProfileRepository fallback;

    private static final Object minecraftServer;
    private static final Reflection.Field<?> gameProfile;

    static {
        Class<?> minecraftServerClass = Reflection.getClass("net.minecraft.server.MinecraftServer");
        Class<?> gpr = Reflection.getClass("com.mojang.authlib.GameProfileRepository");
        gameProfile = Reflection.getField(minecraftServerClass, gpr, 0);
        minecraftServer = Reflection.getTypedMethod(minecraftServerClass, "getServer", minecraftServerClass).invoke(null);
        fallback = (GameProfileRepository) gameProfile.get(minecraftServer);
    }

    @Override
    public void inject() {
        gameProfile.set(minecraftServer, this);
    }

    @Override
    public void findProfilesByNames(String[] strings, Agent agent, ProfileLookupCallback profileLookupCallback) {
        if(agent == Agent.SCROLLS) {
            fallback.findProfilesByNames(strings, agent, profileLookupCallback);
        } else {
            List<String> unknownNames = new ArrayList<>();
            for (String name:strings) {
                SteamwarUser user = SteamwarUser.get(name);
                if(user == null) {
                    unknownNames.add(name);
                    continue;
                }

                profileLookupCallback.onProfileLookupSucceeded(new GameProfile(user.getUUID(), user.getUserName()));
            }
            if(!unknownNames.isEmpty()) {
                fallback.findProfilesByNames(unknownNames.toArray(new String[0]), agent, profileLookupCallback);
            }
        }
    }
}
