package com.nincraft.modpackdownloader.handler;

import com.google.common.base.Strings;
import com.nincraft.modpackdownloader.util.FileSystemHelper;
import com.nincraft.modpackdownloader.util.Reference;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

@Log4j2
public class ForgeHandler {
	public static void downloadForgeInstaller(String minecraftVersion, String forgeVersion) {
		if(Strings.isNullOrEmpty(forgeVersion) || Strings.isNullOrEmpty(minecraftVersion)){
			log.debug("No Forge or Minecraft version found in manifest, skipping");
			return;
		}

		log.info(String.format("Downloading Forge version %s", forgeVersion));

		String forgeId = forgeVersion.substring(forgeVersion.indexOf("-") + 1);
		String forgeURL = Reference.forgeURL + minecraftVersion + "-" + forgeId + "-" + minecraftVersion +
				"/forge-" + minecraftVersion + "-" + forgeId + "-" + minecraftVersion + "-installer.jar";
		String forgeFileName = "forge-" + minecraftVersion + "-" + forgeId + "-" + minecraftVersion + "-installer.jar";
		File forge = FileSystemHelper.getDownloadedFile(forgeFileName);

		if (!FileSystemHelper.isInLocalRepo("forge", forgeFileName) || Reference.forceDownload) {
			val downloadedFile = FileSystemHelper.getDownloadedFile(forgeFileName);
			try {
				FileUtils.copyURLToFile(new URL(forgeURL), downloadedFile);
			} catch (final IOException e) {
				log.error(String.format("Could not download %s.", forgeFileName), e.getMessage());
				return;
			}
			FileSystemHelper.copyToLocalRepo("forge", downloadedFile);
		} else {
			FileSystemHelper.copyFromLocalRepo("forge", forgeFileName, Reference.modFolder);
		}

		log.info(String.format("Completed downloading Forge version %s", forgeFileName));
	}
}

@@ -493,16 +493,17 @@
 ) %7B%0A%09%09if
+ 
 (Strings
@@ -574,16 +574,17 @@
 ersion))
+ 
 %7B%0A%09%09%09log
@@ -834,32 +834,27 @@
 orge
-URL = Reference.
+FileName = %22
 forge
-URL
+-%22
  + m
@@ -888,49 +888,48 @@
 geId
- + %22-%22 + minecraftVersion +%0A%09%09%09%09%22/
+;%0A%09%09String forgeURL = Reference.
 forge
--%22
+URL
  + m
@@ -955,33 +955,33 @@
 -%22 + forgeId
- + %22-%22 + 
+;%0A%09%09if (!
 minecraftVer
@@ -988,38 +988,33 @@
 sion
- + %22-installer.jar%22;%0A%09%09String 
+.startsWith(%221.8%22)) %7B%0A%09%09%09
 forg
@@ -1019,32 +1019,28 @@
 rgeFileName 
++
 = %22
-forge
 -%22 + minecra
@@ -1052,26 +1052,24 @@
 sion
- + %22-%22 + 
+;%0A%09%09%09
 forge
-Id
+URL
  +
+=
  %22-%22
@@ -1087,18 +1087,40 @@
 tVersion
+;%0A%09%09%7D%0A%09%09forgeFileName
  +
+=
  %22-insta
@@ -1136,56 +1136,26 @@
 ;%0A%09%09
-File forge = FileSystemHelper.getDownloadedFile(
+forgeURL += %22/%22 + 
 forg
@@ -1163,17 +1163,16 @@
 FileName
-)
 ;%0A%0A%09%09if 

Fix some Forge URL formatting between MC versions