package com.newhive.scammerradar.manager.submanager;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.newhive.scammerradar.classes.Player;
import com.newhive.scammerradar.classes.PlayerMapAdapter;
import com.newhive.scammerradar.enums.ListEnum;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.naming.ServiceUnavailableException;

public class ServiceManager {
   private final String scammerNameURL = "https://api.scammerradar.de/jupiter";
   private final String mmNameURL = "https://api.scammerradar.de/neptun";
   private final String scammerUuidURL = "https://api.scammerradar.de/saturn";
   private final String mmUuidURL = "https://api.scammerradar.de/erde";
   private final String scammerNoticeURL = "https://api.scammerradar.de/mars";
   private final LocalDateTime lastUpdated = LocalDateTime.now();
   private final HashMap<ListEnum, HashMap<String, Player>> map = new HashMap();
   private final String apiKey = "FranECElDExcebOWBAK";

   public HashMap<ListEnum, HashMap<String, Player>> getPublicLists() throws ServiceUnavailableException {
      if (Duration.between(this.lastUpdated, LocalDateTime.now()).toMinutes() <= 15L && !this.map.isEmpty()) {
         return this.map;
      } else {
         try {
            this.map.put(ListEnum.SCAMMERRADAR, this.updateListFromURLs("https://api.scammerradar.de/saturn", "https://api.scammerradar.de/jupiter", "https://api.scammerradar.de/mars"));
            this.map.put(ListEnum.MM, this.updateListFromURLs("https://api.scammerradar.de/erde", "https://api.scammerradar.de/neptun", ""));
         } catch (ServiceUnavailableException var2) {
            this.map.put(ListEnum.SCAMMERRADAR, new HashMap());
            this.map.put(ListEnum.MM, new HashMap());
            throw new ServiceUnavailableException();
         }

         return this.map;
      }
   }

   private HashMap<String, Player> updateListFromURL(String url) throws ServiceUnavailableException {
      Gson gson = (new GsonBuilder()).registerTypeAdapter(HashMap.class, new PlayerMapAdapter()).setPrettyPrinting().create();

      List<Player> list;
      try {
         BufferedReader reader = new BufferedReader(new InputStreamReader((new URL(url)).openStream()));
         list = (List)gson.fromJson(reader, (new TypeToken<List<Player>>() {
         }).getType());
         reader.close();
      } catch (IOException var7) {
         throw new ServiceUnavailableException();
      }

      HashMap<String, Player> map = new HashMap();

      for(Player player : list) {
         map.put(player.getName(), player);
      }

      return map;
   }

   private List<String> readJsonArray(String url, Gson gson) throws ServiceUnavailableException {
      try {
         HttpURLConnection connection = (HttpURLConnection)(new URL(url)).openConnection();
         connection.setRequestMethod("GET");
         connection.setRequestProperty("Accept", "application/json");
         connection.setRequestProperty("X-API-Key", "FranECElDExcebOWBAK");
         connection.setConnectTimeout(5000);
         connection.setReadTimeout(5000);
         int responseCode = connection.getResponseCode();
         if (responseCode != 200) {
            throw new IOException("HTTP-Fehlercode: " + responseCode);
         } else {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            List var6;
            try {
               var6 = (List)gson.fromJson(reader, (new TypeToken<List<String>>() {
               }).getType());
            } catch (Throwable var9) {
               try {
                  reader.close();
               } catch (Throwable var8) {
                  var9.addSuppressed(var8);
               }

               throw var9;
            }

            reader.close();
            return var6;
         }
      } catch (JsonParseException | IOException var10) {
         throw new ServiceUnavailableException();
      }
   }

   private List<String> extractFormattedUUIDsFromUrls(List<String> uuidUrls) {
      List<String> formattedUUIDs = new ArrayList();

      for(String url : uuidUrls) {
         String rawUUID = url.substring(url.lastIndexOf("/") + 1);
         String formatted = rawUUID.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5");
         formattedUUIDs.add(formatted);
      }

      return formattedUUIDs;
   }

   private List<String> extractFormattedNamesFromUrls(List<String> nameURLs) {
      List<String> formattedNames = new ArrayList();

      for(String name : nameURLs) {
         String formatted = name.substring(name.lastIndexOf("/") + 1);
         formattedNames.add(formatted);
      }

      return formattedNames;
   }

   private HashMap<String, Player> updateListFromURLs(String urlUUIDs, String urlNames, String urlNotices) throws ServiceUnavailableException {
      Gson gson = new Gson();
      List<String> names = this.readJsonArray(urlNames, gson);
      List<String> uuids = this.readJsonArray(urlUUIDs, gson);
      List<String> notices;
      if (urlNotices.isEmpty()) {
         notices = new ArrayList(Collections.nCopies(names.size(), ""));
      } else {
         notices = this.readJsonArray(urlNotices, gson);
      }

      if (notices.size() != names.size()) {
         notices = new ArrayList(Collections.nCopies(names.size(), ""));
      }

      uuids = this.extractFormattedUUIDsFromUrls(uuids);
      names = this.extractFormattedNamesFromUrls(names);
      if (names.size() != uuids.size()) {
         throw new ServiceUnavailableException("Datenlängen stimmen nicht überein.");
      } else {
         HashMap<String, Player> map = new HashMap();

         for(int i = 0; i < names.size(); ++i) {
            Player player = new Player((String)names.get(i), (String)uuids.get(i), (String)notices.get(i));
            if (map.containsKey(player.name)) {
               System.out.println("Doppelter Name gefunden: " + player.name);
            }

            map.put(player.getName(), player);
         }

         return map;
      }
   }
}
