package net.minecraft.launcher.updater;

import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mojang.launcher.OperatingSystem;
import com.mojang.launcher.game.process.GameProcessBuilder;
import com.mojang.launcher.updater.VersionSyncInfo;
import com.mojang.launcher.updater.download.Downloadable;
import com.mojang.launcher.versions.CompleteVersion;
import com.mojang.launcher.versions.ReleaseType;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import net.minecraft.launcher.CompatibilityRule;
import net.minecraft.launcher.CurrentLaunchFeatureMatcher;
import net.minecraft.launcher.Launcher;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class CompleteMinecraftVersion implements CompleteVersion {
   private static final Logger LOGGER = LogManager.getLogger();
   private String inheritsFrom;
   private String id;
   private Date time;
   private Date releaseTime;
   private ReleaseType type;
   private String minecraftArguments;
   private List<Library> libraries;
   private String mainClass;
   private int minimumLauncherVersion;
   private String incompatibilityReason;
   private String assets;
   private List<CompatibilityRule> compatibilityRules;
   private String jar;
   private CompleteMinecraftVersion savableVersion;
   private transient boolean synced = false;
   private Map<DownloadType, DownloadInfo> downloads = Maps.newEnumMap(DownloadType.class);
   private AssetIndexInfo assetIndex;
   private Map<ArgumentType, List<Argument>> arguments;

   public CompleteMinecraftVersion() {
   }

   public CompleteMinecraftVersion(CompleteMinecraftVersion version) {
      this.inheritsFrom = version.inheritsFrom;
      this.id = version.id;
      this.time = version.time;
      this.releaseTime = version.releaseTime;
      this.type = version.type;
      this.minecraftArguments = version.minecraftArguments;
      this.mainClass = version.mainClass;
      this.minimumLauncherVersion = version.minimumLauncherVersion;
      this.incompatibilityReason = version.incompatibilityReason;
      this.assets = version.assets;
      this.jar = version.jar;
      this.downloads = version.downloads;
      Iterator var2;
      if (version.libraries != null) {
         this.libraries = Lists.newArrayList();
         var2 = version.getLibraries().iterator();

         while(var2.hasNext()) {
            Library library = (Library)var2.next();
            this.libraries.add(new Library(library));
         }
      }

      if (version.arguments != null) {
         this.arguments = Maps.newEnumMap(ArgumentType.class);
         var2 = version.arguments.entrySet().iterator();

         while(var2.hasNext()) {
            Entry<ArgumentType, List<Argument>> entry = (Entry)var2.next();
            this.arguments.put(entry.getKey(), new ArrayList((Collection)entry.getValue()));
         }
      }

      if (version.compatibilityRules != null) {
         this.compatibilityRules = Lists.newArrayList();
         var2 = version.compatibilityRules.iterator();

         while(var2.hasNext()) {
            CompatibilityRule compatibilityRule = (CompatibilityRule)var2.next();
            this.compatibilityRules.add(new CompatibilityRule(compatibilityRule));
         }
      }

   }

   public String getId() {
      return this.id;
   }

   public ReleaseType getType() {
      return this.type;
   }

   public Date getUpdatedTime() {
      return this.time;
   }

   public Date getReleaseTime() {
      return this.releaseTime;
   }

   public List<Library> getLibraries() {
      return this.libraries;
   }

   public String getMainClass() {
      return this.mainClass;
   }

   public String getJar() {
      return this.jar == null ? this.id : this.jar;
   }

   public void setType(ReleaseType type) {
      if (type == null) {
         throw new IllegalArgumentException("Release type cannot be null");
      } else {
         this.type = type;
      }
   }

   public Collection<Library> getRelevantLibraries(CompatibilityRule.FeatureMatcher featureMatcher) {
      List<Library> result = new ArrayList();
      Iterator var3 = this.libraries.iterator();

      while(var3.hasNext()) {
         Library library = (Library)var3.next();
         if (library.appliesToCurrentEnvironment(featureMatcher)) {
            result.add(library);
         }
      }

      return result;
   }

   public Collection<File> getClassPath(OperatingSystem os, File base, CompatibilityRule.FeatureMatcher featureMatcher) {
      Collection<Library> libraries = this.getRelevantLibraries(featureMatcher);
      Collection<File> result = new ArrayList();
      Iterator var6 = libraries.iterator();

      while(var6.hasNext()) {
         Library library = (Library)var6.next();
         if (library.getNatives() == null) {
            result.add(new File(base, "libraries/" + library.getArtifactPath()));
         }
      }

      result.add(new File(base, "versions/" + this.getJar() + "/" + this.getJar() + ".jar"));
      return result;
   }

   public Set<String> getRequiredFiles(OperatingSystem os) {
      Set<String> neededFiles = new HashSet();
      Iterator var3 = this.getRelevantLibraries(this.createFeatureMatcher()).iterator();

      while(var3.hasNext()) {
         Library library = (Library)var3.next();
         if (library.getNatives() != null) {
            String natives = (String)library.getNatives().get(os);
            if (natives != null) {
               neededFiles.add("libraries/" + library.getArtifactPath(natives));
            }
         } else {
            neededFiles.add("libraries/" + library.getArtifactPath());
         }
      }

      return neededFiles;
   }

   public Set<Downloadable> getRequiredDownloadables(OperatingSystem os, Proxy proxy, File targetDirectory, boolean ignoreLocalFiles) throws MalformedURLException {
      Set<Downloadable> neededFiles = new HashSet();
      Iterator var6 = this.getRelevantLibraries(this.createFeatureMatcher()).iterator();

      while(var6.hasNext()) {
         Library library = (Library)var6.next();
         String file = null;
         String classifier = null;
         if (library.getNatives() != null) {
            classifier = (String)library.getNatives().get(os);
            if (classifier != null) {
               file = library.getArtifactPath(classifier);
            }
         } else {
            file = library.getArtifactPath();
         }

         if (file != null) {
            File local = new File(targetDirectory, "libraries/" + file);
            Downloadable download = library.createDownload(proxy, file, local, ignoreLocalFiles, classifier);
            if (download != null) {
               neededFiles.add(download);
            }
         }
      }

      return neededFiles;
   }

   public String toString() {
      return "CompleteVersion{id='" + this.id + '\'' + ", updatedTime=" + this.time + ", releasedTime=" + this.time + ", type=" + this.type + ", libraries=" + this.libraries + ", mainClass='" + this.mainClass + '\'' + ", jar='" + this.jar + '\'' + ", minimumLauncherVersion=" + this.minimumLauncherVersion + '}';
   }

   public String getMinecraftArguments() {
      return this.minecraftArguments;
   }

   public int getMinimumLauncherVersion() {
      return this.minimumLauncherVersion;
   }

   public boolean appliesToCurrentEnvironment() {
      if (this.compatibilityRules == null) {
         return true;
      } else {
         CompatibilityRule.Action lastAction = CompatibilityRule.Action.DISALLOW;
         Iterator var2 = this.compatibilityRules.iterator();

         while(var2.hasNext()) {
            CompatibilityRule compatibilityRule = (CompatibilityRule)var2.next();
            CompatibilityRule.Action action = compatibilityRule.getAppliedAction(new CurrentLaunchFeatureMatcher(Launcher.getCurrentInstance().getProfileManager().getSelectedProfile(), this));
            if (action != null) {
               lastAction = action;
            }
         }

         return lastAction == CompatibilityRule.Action.ALLOW;
      }
   }

   public String getIncompatibilityReason() {
      return this.incompatibilityReason;
   }

   public boolean isSynced() {
      return this.synced;
   }

   public void setSynced(boolean synced) {
      this.synced = synced;
   }

   public String getInheritsFrom() {
      return this.inheritsFrom;
   }

   public CompleteMinecraftVersion resolve(MinecraftVersionManager versionManager) throws IOException {
      Set<String> s = new HashSet();
      return this.resolve(versionManager, s);
   }

   protected CompleteMinecraftVersion resolve(MinecraftVersionManager versionManager, Set<String> resolvedSoFar) throws IOException {
      if (this.inheritsFrom == null) {
         return this;
      } else if (!resolvedSoFar.add(this.id)) {
         throw new IllegalStateException("Circular dependency detected");
      } else {
         VersionSyncInfo parentSync = versionManager.getVersionSyncInfo(this.inheritsFrom);
         CompleteMinecraftVersion parent = versionManager.getLatestCompleteVersion(parentSync).resolve(versionManager, resolvedSoFar);
         CompleteMinecraftVersion result = new CompleteMinecraftVersion(parent);
         if (!parentSync.isInstalled() || !parentSync.isUpToDate() || parentSync.getLatestSource() != VersionSyncInfo.VersionSource.LOCAL) {
            versionManager.installVersion(parent);
         }

         result.savableVersion = this;
         result.inheritsFrom = null;
         result.id = this.id;
         result.time = this.time;
         result.releaseTime = this.releaseTime;
         result.type = this.type;
         if (this.minecraftArguments != null) {
            result.minecraftArguments = this.minecraftArguments;
         }

         if (this.mainClass != null) {
            result.mainClass = this.mainClass;
         }

         if (this.incompatibilityReason != null) {
            result.incompatibilityReason = this.incompatibilityReason;
         }

         if (this.assets != null) {
            result.assets = this.assets;
         }

         if (this.jar != null) {
            result.jar = this.jar;
         }

         if (this.libraries != null) {
            List<Library> newLibraries = Lists.newArrayList();
            Iterator var7 = this.libraries.iterator();

            Library library;
            while(var7.hasNext()) {
               library = (Library)var7.next();
               newLibraries.add(new Library(library));
            }

            var7 = result.libraries.iterator();

            while(var7.hasNext()) {
               library = (Library)var7.next();
               newLibraries.add(library);
            }

            result.libraries = newLibraries;
         }

         Iterator var9;
         if (this.arguments != null) {
            if (result.arguments == null) {
               result.arguments = new EnumMap(ArgumentType.class);
            }

            Entry entry;
            Object arguments;
            for(var9 = this.arguments.entrySet().iterator(); var9.hasNext(); ((List)arguments).addAll((Collection)entry.getValue())) {
               entry = (Entry)var9.next();
               arguments = (List)result.arguments.get(entry.getKey());
               if (arguments == null) {
                  arguments = new ArrayList();
                  result.arguments.put(entry.getKey(), arguments);
               }
            }
         }

         if (this.compatibilityRules != null) {
            var9 = this.compatibilityRules.iterator();

            while(var9.hasNext()) {
               CompatibilityRule compatibilityRule = (CompatibilityRule)var9.next();
               result.compatibilityRules.add(new CompatibilityRule(compatibilityRule));
            }
         }

         return result;
      }
   }

   public CompleteMinecraftVersion getSavableVersion() {
      return (CompleteMinecraftVersion)Objects.firstNonNull(this.savableVersion, this);
   }

   public DownloadInfo getDownloadURL(DownloadType type) {
      return (DownloadInfo)this.downloads.get(type);
   }

   public AssetIndexInfo getAssetIndex() {
      if (this.assetIndex == null) {
         this.assetIndex = new AssetIndexInfo((String)Objects.firstNonNull(this.assets, "legacy"));
      }

      return this.assetIndex;
   }

   public CompatibilityRule.FeatureMatcher createFeatureMatcher() {
      return new CurrentLaunchFeatureMatcher(Launcher.getCurrentInstance().getProfileManager().getSelectedProfile(), this);
   }

   public void addArguments(ArgumentType type, CompatibilityRule.FeatureMatcher featureMatcher, GameProcessBuilder builder, StrSubstitutor substitutor) {
      if (this.arguments != null) {
         List<Argument> args = (List)this.arguments.get(type);
         if (args != null) {
            Iterator var6 = args.iterator();

            while(var6.hasNext()) {
               Argument argument = (Argument)var6.next();
               argument.apply(builder, featureMatcher, substitutor);
            }
         }
      } else if (this.minecraftArguments != null) {
         if (type == ArgumentType.GAME) {
            String[] var9 = this.minecraftArguments.split(" ");
            int var10 = var9.length;

            for(int var11 = 0; var11 < var10; ++var11) {
               String arg = var9[var11];
               builder.withArguments(substitutor.replace(arg));
            }

            if (featureMatcher.hasFeature("is_demo_user", true)) {
               builder.withArguments("--demo");
            }

            if (featureMatcher.hasFeature("has_custom_resolution", true)) {
               builder.withArguments("--width", substitutor.replace("${resolution_width}"), "--height", substitutor.replace("${resolution_height}"));
            }
         } else if (type == ArgumentType.JVM) {
            if (OperatingSystem.getCurrentPlatform() == OperatingSystem.WINDOWS) {
               builder.withArguments("-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump");
               if (Launcher.getCurrentInstance().usesWinTenHack()) {
                  builder.withArguments("-Dos.name=Windows 10", "-Dos.version=10.0");
               }
            } else if (OperatingSystem.getCurrentPlatform() == OperatingSystem.OSX) {
               builder.withArguments(substitutor.replace("-Xdock:icon=${asset=icons/minecraft.icns}"), "-Xdock:name=Minecraft");
            }

            builder.withArguments(substitutor.replace("-Djava.library.path=${natives_directory}"));
            builder.withArguments(substitutor.replace("-Dminecraft.launcher.brand=${launcher_name}"));
            builder.withArguments(substitutor.replace("-Dminecraft.launcher.version=${launcher_version}"));
            builder.withArguments(substitutor.replace("-Dminecraft.client.jar=${primary_jar}"));
            builder.withArguments("-cp", substitutor.replace("${classpath}"));
         }
      }

   }
}
