summaryrefslogtreecommitdiff
path: root/archived/projt-launcher/launcher/modplatform/flame/FlameInstanceCreationTask.cpp
blob: 8786509646095797b44fa7973dc34565745972c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: 2026 Project Tick
// SPDX-FileContributor: Project Tick Team
/*
 *  ProjT Launcher - Minecraft Launcher
 *  Copyright (C) 2026 Project Tick
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3.
 *
 *  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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, write to the Free Software Foundation,
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * === Upstream License Block (Do Not Modify) ==============================
 *
 *
 *
 *  Prism Launcher - Minecraft Launcher
 *  Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3.
 *
 *  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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, write to the Free Software Foundation,
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * This file incorporates work covered by the following copyright and
 * permission notice:
 *
 *      Copyright 2013-2021 MultiMC Contributors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 *
 * ======================================================================== */

#include "FlameInstanceCreationTask.h"

#include "QObjectPtr.h"
#include "minecraft/mod/tasks/LocalResourceUpdateTask.hpp"
#include "modplatform/flame/FileResolvingTask.h"
#include "modplatform/flame/FlameAPI.h"
#include "modplatform/flame/FlameModIndex.h"
#include "modplatform/flame/PackManifest.h"

#include "Application.h"
#include "FileSystem.h"
#include "InstanceList.h"
#include "Json.h"

#include "minecraft/MinecraftInstance.h"
#include "minecraft/PackProfile.h"

#include "modplatform/helpers/OverrideUtils.h"

#include "settings/INISettingsObject.h"

#include "tasks/ConcurrentTask.h"
#include "ui/dialogs/BlockedModsDialog.h"
#include "ui/dialogs/CustomMessageBox.h"

#include <QDebug>
#include <QFileInfo>

#include "meta/Index.hpp"
#include "HardwareInfo.h"
#include "minecraft/World.h"
#include "minecraft/mod/tasks/LocalResourceParse.hpp"
#include "net/ApiDownload.h"
#include "ui/pages/modplatform/OptionalModDialog.h"

static const FlameAPI api;

bool FlameCreationTask::abort()
{
	if (!canAbort())
		return false;

	if (m_processUpdateFileInfoJob)
		m_processUpdateFileInfoJob->abort();
	if (m_filesJob)
		m_filesJob->abort();
	if (m_modIdResolver)
		m_modIdResolver->abort();

	return InstanceCreationTask::abort();
}

bool FlameCreationTask::updateInstance()
{
	auto instance_list = APPLICATION->instances();

	// Note: Duplicate modpack detection uses managed name or instance ID lookup.
	// If multiple installations exist, the first match is updated.
	InstancePtr inst;
	if (auto original_id = originalInstanceID(); !original_id.isEmpty())
	{
		inst = instance_list->getInstanceById(original_id);
		Q_ASSERT(inst);
	}
	else
	{
		// Duplicate Detection: Check for duplicates before assuming
		auto all_instances = instance_list->getAllInstancesByManagedName(originalName());

		if (all_instances.size() > 1)
		{
			emitFailed(tr("Multiple instances found for this modpack. Please update the specific instance you want to "
						  "modify to avoid ambiguity."));
			return false;
		}

		if (all_instances.size() == 1)
		{
			inst = all_instances.first();
		}
		else
		{
			// Fallback to name-based lookup if not found by managed ID
			inst = instance_list->getInstanceById(originalName());
		}

		if (!inst)
		{
			// New instance creation flow - return false to call createInstance()
			return false;
		}
	}

	QString index_path(FS::PathCombine(m_stagingPath, "manifest.json"));

	try
	{
		Flame::loadManifest(m_pack, index_path);
	}
	catch (const JSONValidationError& e)
	{
		setError(tr("Could not understand pack manifest:\n") + e.cause());
		return false;
	}

	auto version_id	 = inst->getManagedPackVersionName();
	auto version_str = !version_id.isEmpty() ? tr(" (version %1)").arg(version_id) : "";

	if (shouldConfirmUpdate())
	{
		auto should_update = askIfShouldUpdate(m_parent, version_str);
		if (should_update == ShouldUpdate::SkipUpdating)
			return false;
		if (should_update == ShouldUpdate::Cancel)
		{
			m_abort = true;
			return false;
		}
	}

	QDir old_inst_dir(inst->instanceRoot());

	QString old_index_folder(FS::PathCombine(old_inst_dir.absolutePath(), "flame"));
	QString old_index_path(FS::PathCombine(old_index_folder, "manifest.json"));

	QFileInfo old_index_file(old_index_path);
	if (old_index_file.exists())
	{
		Flame::Manifest old_pack;
		Flame::loadManifest(old_pack, old_index_path);

		auto& old_files = old_pack.files;

		auto& files = m_pack.files;

		// Remove repeated files, we don't need to download them!
		auto files_iterator = files.begin();
		while (files_iterator != files.end())
		{
			auto const& file = files_iterator;

			auto old_file = old_files.find(file.key());
			if (old_file != old_files.end())
			{
				// We found a match, but is it a different version?
				if (old_file->fileId == file->fileId)
				{
					qDebug() << "Removed file at" << file->targetFolder << "with id" << file->fileId
							 << "from list of downloads";

					old_files.remove(file.key());
					files_iterator = files.erase(files_iterator);

					if (files_iterator != files.begin())
						files_iterator--;
				}
			}

			files_iterator++;
		}

		QDir old_minecraft_dir(inst->gameRoot());

		// We will remove all the previous overrides, to prevent duplicate files!
		// Note: Overrides intentionally replace all files on update - this matches modpack author expectations.
		auto old_overrides = Override::readOverrides("overrides", old_index_folder);
		for (const auto& entry : old_overrides)
		{
			if (entry.isEmpty())
				continue;

			// Skip removal of .disabled files (user-disabled mods should be preserved)
			if (entry.endsWith(".disabled", Qt::CaseInsensitive))
			{
				qDebug() << "Preserving disabled mod:" << entry;
				continue;
			}

			qDebug() << "Scheduling" << entry << "for removal";
			m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(entry));
			m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(entry + ".disabled"));
		}

		// Remove remaining old files (we need to do an API request to know which ids are which files...)
		QStringList fileIds;

		for (auto& file : old_files)
		{
			fileIds.append(QString::number(file.fileId));
		}

		auto raw_response = std::make_shared<QByteArray>();
		auto job		  = api.getFiles(fileIds, raw_response);

		QEventLoop loop;

		connect(job.get(),
				&Task::succeeded,
				this,
				[this, raw_response, fileIds, old_inst_dir, &old_files, old_minecraft_dir]
				{
					// Parse the API response
					QJsonParseError parse_error{};
					auto doc = QJsonDocument::fromJson(*raw_response, &parse_error);
					if (parse_error.error != QJsonParseError::NoError)
					{
						qWarning() << "Error while parsing JSON response from Flame files task at "
								   << parse_error.offset << " reason: " << parse_error.errorString();
						qWarning() << *raw_response;
						return;
					}

					try
					{
						QJsonArray entries;
						if (fileIds.size() == 1)
							entries = { Json::requireObject(Json::requireObject(doc), "data") };
						else
							entries = Json::requireArray(Json::requireObject(doc), "data");

						for (auto entry : entries)
						{
							auto entry_obj = Json::requireObject(entry);

							Flame::File file;
							// We don't care about blocked mods, we just need local data to delete the file
							file.version = FlameMod::loadIndexedPackVersion(entry_obj);
							auto id		 = Json::requireInteger(entry_obj, "id");
							old_files.insert(id, file);
						}
					}
					catch (Json::JsonException& e)
					{
						qCritical() << e.cause() << e.what();
					}

					// Delete the files
					for (auto& file : old_files)
					{
						if (file.version.fileName.isEmpty() || file.targetFolder.isEmpty())
							continue;

						QString relative_path(FS::PathCombine(file.targetFolder, file.version.fileName));
						qDebug() << "Scheduling" << relative_path << "for removal";
						m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(relative_path));
						if (relative_path.endsWith(".disabled"))
						{ // remove it if it was enabled/disabled by user
							m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(relative_path.chopped(9)));
						}
						else
						{
							m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(relative_path + ".disabled"));
						}
					}
				});
		connect(job.get(),
				&Task::failed,
				this,
				[](QString reason) { qCritical() << "Failed to get files: " << reason; });
		connect(job.get(), &Task::finished, &loop, &QEventLoop::quit);

		m_processUpdateFileInfoJob = job;
		job->start();

		loop.exec();

		m_processUpdateFileInfoJob = nullptr;
	}
	else
	{
		// We don't have an old index file, so we may duplicate stuff!
		auto dialog = CustomMessageBox::selectable(
			m_parent,
			tr("No index file."),
			tr("We couldn't find a suitable index file for the older version. This may cause some "
			   "of the files to be duplicated. Do you want to continue?"),
			QMessageBox::Warning,
			QMessageBox::Ok | QMessageBox::Cancel);

		if (dialog->exec() == QDialog::DialogCode::Rejected)
		{
			m_abort = true;
			return false;
		}
	}

	setOverride(true, inst->id());
	qDebug() << "Will override instance!";

	m_instance = inst;

	// We let it go through the createInstance() stage, just with a couple modifications for updating
	return false;
}

QString FlameCreationTask::getVersionForLoader(QString uid,
											   QString loaderType,
											   QString loaderVersion,
											   QString mcVersion)
{
	if (loaderVersion == "recommended")
	{
		auto vlist = APPLICATION->metadataIndex()->component(uid);
		if (!vlist)
		{
			setError(tr("Failed to get local metadata index for %1").arg(uid));
			return {};
		}

		if (!vlist->isLoaded())
		{
			QEventLoop loadVersionLoop;
			auto task = vlist->getLoadTask();
			connect(task.get(), &Task::finished, &loadVersionLoop, &QEventLoop::quit);
			if (!task->isRunning())
				task->start();

			loadVersionLoop.exec();
		}

		for (auto version : vlist->allVersions())
		{
			// first recommended build we find, we use.
			if (!version->isStable())
				continue;
			auto reqs = version->dependencies();

			// filter by minecraft version, if the loader depends on a certain version.
			// not all mod loaders depend on a given Minecraft version, so we won't do this
			// filtering for those loaders.
			if (loaderType == "forge" || loaderType == "neoforge")
			{
				auto iter = std::find_if(reqs.begin(),
										 reqs.end(),
										 [mcVersion](const projt::meta::ComponentDependency& req)
										 { return req.uid == "net.minecraft" && req.equalsVersion == mcVersion; });
				if (iter == reqs.end())
					continue;
			}
			return version->descriptor();
		}

		setError(tr("Failed to find version for %1 loader").arg(loaderType));
		return {};
	}

	if (loaderVersion.isEmpty())
	{
		emitFailed(tr("No loader version set for modpack!"));
		return {};
	}

	return loaderVersion;
}

std::unique_ptr<MinecraftInstance> FlameCreationTask::createInstance()
{
	QEventLoop loop;

	QString parent_folder(FS::PathCombine(m_stagingPath, "flame"));

	try
	{
		QString index_path(FS::PathCombine(m_stagingPath, "manifest.json"));
		if (!m_pack.is_loaded)
			Flame::loadManifest(m_pack, index_path);

		// Keep index file in case we need it some other time (like when changing versions)
		QString new_index_place(FS::PathCombine(parent_folder, "manifest.json"));
		FS::ensureFilePathExists(new_index_place);
		FS::move(index_path, new_index_place);
	}
	catch (const JSONValidationError& e)
	{
		setError(tr("Could not understand pack manifest:\n") + e.cause());
		return nullptr;
	}

	if (!m_pack.overrides.isEmpty())
	{
		QString overridePath = FS::PathCombine(m_stagingPath, m_pack.overrides);
		if (QFile::exists(overridePath))
		{
			// Create a list of overrides in "overrides.txt" inside flame/
			Override::createOverrides("overrides", parent_folder, overridePath);

			QString mcPath = FS::PathCombine(m_stagingPath, "minecraft");
			if (!FS::move(overridePath, mcPath))
			{
				setError(tr("Could not rename the overrides folder:\n") + m_pack.overrides);
				return nullptr;
			}
		}
		else
		{
			logWarning(tr("The specified overrides folder (%1) is missing. Maybe the modpack was already used before?")
						   .arg(m_pack.overrides));
		}
	}

	QString loaderType;
	QString loaderUid;
	QString loaderVersion;

	for (auto& loader : m_pack.minecraft.modLoaders)
	{
		auto id = loader.id;
		if (id.startsWith("neoforge-"))
		{
			id.remove("neoforge-");
			if (id.startsWith("1.20.1-"))
				id.remove("1.20.1-"); // this is a mess for curseforge
			loaderType = "neoforge";
			loaderUid  = "net.neoforged";
		}
		else if (id.startsWith("forge-"))
		{
			id.remove("forge-");
			loaderType = "forge";
			loaderUid  = "net.minecraftforge";
		}
		else if (id.startsWith("fabric-"))
		{
			id.remove("fabric-");
			loaderType = "fabric";
			loaderUid  = "net.fabricmc.fabric-loader";
		}
		else if (id.startsWith("quilt-"))
		{
			id.remove("quilt-");
			loaderType = "quilt";
			loaderUid  = "org.quiltmc.quilt-loader";
		}
		else
		{
			logWarning(tr("Unknown mod loader in manifest: %1").arg(id));
			continue;
		}
		loaderVersion = id;
	}

	QString configPath	  = FS::PathCombine(m_stagingPath, "instance.cfg");
	auto instanceSettings = std::make_shared<INISettingsObject>(configPath);
	auto createdInstance  = std::make_unique<MinecraftInstance>(m_globalSettings, instanceSettings, m_stagingPath);
	auto& instance		  = *createdInstance;
	auto mcVersion = m_pack.minecraft.version;

	// Hack to correct some 'special sauce'...
	if (mcVersion.endsWith('.'))
	{
		static const QRegularExpression s_regex("[.]+$");
		mcVersion.remove(s_regex);
		logWarning(tr("Mysterious trailing dots removed from Minecraft version while importing pack."));
	}

	auto components = instance.getPackProfile();
	components->buildingFromScratch();
	components->setComponentVersion("net.minecraft", mcVersion, true);
	if (!loaderType.isEmpty())
	{
		auto version = getVersionForLoader(loaderUid, loaderType, loaderVersion, mcVersion);
		if (version.isEmpty())
			return nullptr;
		components->setComponentVersion(loaderUid, version);
	}

	if (m_instIcon != "default")
	{
		instance.setIconKey(m_instIcon);
	}
	else
	{
		if (m_pack.name.contains("Direwolf20"))
		{
			instance.setIconKey("steve");
		}
		else if (m_pack.name.contains("FTB") || m_pack.name.contains("Feed The Beast"))
		{
			instance.setIconKey("ftb_logo");
		}
		else
		{
			instance.setIconKey("flame");
		}
	}

	int recommendedRAM = m_pack.minecraft.recommendedRAM;

	// only set memory if this is a fresh instance
	if (m_instance == nullptr && recommendedRAM > 0)
	{
		const uint64_t sysMiB = HardwareInfo::totalRamMiB();
		const uint64_t max	  = sysMiB * 0.9;
		if (static_cast<uint64_t>(recommendedRAM) > max)
		{
			logWarning(tr("The recommended memory of the modpack exceeds 90% of your system RAM—reducing it from %1 "
						  "MiB to %2 MiB!")
						   .arg(recommendedRAM)
						   .arg(max));
			recommendedRAM = max;
		}

		instance.settings()->set("OverrideMemory", true);
		instance.settings()->set("MaxMemAlloc", recommendedRAM);
	}

	QString jarmodsPath = FS::PathCombine(m_stagingPath, "minecraft", "jarmods");
	QFileInfo jarmodsInfo(jarmodsPath);
	if (jarmodsInfo.isDir())
	{
		// install all the jar mods
		qDebug() << "Found jarmods:";
		QDir jarmodsDir(jarmodsPath);
		QStringList jarMods;
		for (const auto& info : jarmodsDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files))
		{
			qDebug() << info.fileName();
			jarMods.push_back(info.absoluteFilePath());
		}
		auto profile = instance.getPackProfile();
		profile->installJarMods(jarMods);
		// nuke the original files
		FS::deletePath(jarmodsPath);
	}

	// Don't add managed info to packs without an ID (most likely imported from ZIP)
	if (!m_managedId.isEmpty())
		instance.setManagedPack("flame", m_managedId, m_pack.name, m_managedVersionId, m_pack.version);
	else
		instance.setManagedPack("flame", "", name(), "", "");

	instance.setName(name());

	m_modIdResolver.reset(new Flame::FileResolvingTask(m_pack));
	connect(m_modIdResolver.get(),
			&Flame::FileResolvingTask::succeeded,
			this,
			[this, &loop] { idResolverSucceeded(loop); });
	connect(m_modIdResolver.get(),
			&Flame::FileResolvingTask::failed,
			[this, &loop](QString reason)
			{
				m_modIdResolver.reset();
				setError(tr("Unable to resolve mod IDs:\n") + reason);
				loop.quit();
			});
	connect(m_modIdResolver.get(), &Flame::FileResolvingTask::aborted, &loop, &QEventLoop::quit);
	connect(m_modIdResolver.get(), &Flame::FileResolvingTask::progress, this, &FlameCreationTask::setProgress);
	connect(m_modIdResolver.get(), &Flame::FileResolvingTask::status, this, &FlameCreationTask::setStatus);
	connect(m_modIdResolver.get(),
			&Flame::FileResolvingTask::stepProgress,
			this,
			&FlameCreationTask::propagateStepProgress);
	connect(m_modIdResolver.get(), &Flame::FileResolvingTask::details, this, &FlameCreationTask::setDetails);
	m_modIdResolver->start();

	loop.exec();

	bool did_succeed = getError().isEmpty();

	// Update information of the already installed instance, if any.
	if (m_instance && did_succeed)
	{
		setAbortable(false);
		auto inst = m_instance.value();

		inst->copyManagedPack(instance);
	}

	if (did_succeed)
	{
		return createdInstance;
	}
	return nullptr;
}

void FlameCreationTask::idResolverSucceeded(QEventLoop& loop)
{
	auto results = m_modIdResolver->getResults().files;

	QStringList optionalFiles;
	for (auto& result : results)
	{
		if (!result.required)
		{
			optionalFiles << FS::PathCombine(result.targetFolder, result.version.fileName);
		}
	}

	if (!optionalFiles.empty())
	{
		OptionalModDialog optionalModDialog(m_parent, optionalFiles);
		if (optionalModDialog.exec() == QDialog::Rejected)
		{
			emitAborted();
			loop.quit();
			return;
		}

		m_selectedOptionalMods = optionalModDialog.getResult();
	}

	// first check for blocked mods
	QList<BlockedMod> blocked_mods;
	auto anyBlocked = false;
	for (const auto& result : results.values())
	{
		if (result.resourceType != ModPlatform::ResourceType::Mod)
		{
			m_otherResources.append(std::make_pair(result.version.fileName, result.targetFolder));
		}

		// skip optional mods that were not selected
		if (result.version.downloadUrl.isEmpty())
		{
			BlockedMod blocked_mod;
			blocked_mod.name = result.version.fileName;
			blocked_mod.websiteUrl =
				QString("%1/download/%2").arg(result.pack.websiteUrl, QString::number(result.fileId));
			blocked_mod.hash		 = result.version.hash;
			blocked_mod.matched		 = false;
			blocked_mod.localPath	 = "";
			blocked_mod.targetFolder = result.targetFolder;
			auto fileName			 = result.version.fileName;
			fileName				 = FS::RemoveInvalidPathChars(fileName);
			auto relpath			 = FS::PathCombine(result.targetFolder, fileName);
			blocked_mod.disabled	 = !result.required && !m_selectedOptionalMods.contains(relpath);

			blocked_mods.append(blocked_mod);

			anyBlocked = true;
		}
	}
	if (anyBlocked)
	{
		qWarning() << "Blocked mods found, displaying mod list";

		BlockedModsDialog message_dialog(
			m_parent,
			tr("Blocked mods found"),
			tr("The following files are not available for download in third party launchers.<br/>"
			   "You will need to manually download them and add them to the instance."),
			blocked_mods);

		message_dialog.setModal(true);

		if (message_dialog.exec())
		{
			qDebug() << "Post dialog blocked mods list: " << blocked_mods;
			copyBlockedMods(blocked_mods);
			setupDownloadJob(loop);
		}
		else
		{
			m_modIdResolver.reset();
			setError("Canceled");
			loop.quit();
		}
	}
	else
	{
		setupDownloadJob(loop);
	}
}

void FlameCreationTask::setupDownloadJob(QEventLoop& loop)
{
	m_filesJob.reset(new NetJob(tr("Mod Download Flame"), APPLICATION->network()));
	auto results = m_modIdResolver->getResults().files;

	for (const auto& result : results)
	{
		auto fileName = result.version.fileName;
		fileName	  = FS::RemoveInvalidPathChars(fileName);
		auto relpath  = FS::PathCombine(result.targetFolder, fileName);

		if (!result.required && !m_selectedOptionalMods.contains(relpath))
		{
			relpath += ".disabled";
		}

		relpath	  = FS::PathCombine("minecraft", relpath);
		auto path = FS::PathCombine(m_stagingPath, relpath);

		if (!result.version.downloadUrl.isEmpty())
		{
			qDebug() << "Will download" << result.version.downloadUrl << "to" << path;
			auto dl = Net::ApiDownload::makeFile(result.version.downloadUrl, path);
			m_filesJob->addNetAction(dl);
		}
	}

	connect(m_filesJob.get(),
			&NetJob::finished,
			this,
			[this, &loop]()
			{
				m_filesJob.reset();
				validateOtherResources(loop);
			});
	connect(m_filesJob.get(),
			&NetJob::failed,
			[this](QString reason)
			{
				m_filesJob.reset();
				setError(reason);
			});
	connect(m_filesJob.get(),
			&NetJob::progress,
			this,
			[this](qint64 current, qint64 total)
			{
				setDetails(tr("%1 out of %2 complete").arg(current).arg(total));
				setProgress(current, total);
			});
	connect(m_filesJob.get(), &NetJob::stepProgress, this, &FlameCreationTask::propagateStepProgress);

	setStatus(tr("Downloading mods..."));
	m_filesJob->start();
}

/// @brief copy the matched blocked mods to the instance staging area
/// @param blocked_mods list of the blocked mods and their matched paths
void FlameCreationTask::copyBlockedMods(QList<BlockedMod> const& blocked_mods)
{
	setStatus(tr("Copying Blocked Mods..."));
	setAbortable(false);
	int i	  = 0;
	int total = blocked_mods.length();
	setProgress(i, total);
	for (auto const& mod : blocked_mods)
	{
		if (!mod.matched)
		{
			qDebug() << mod.name << "was not matched to a local file, skipping copy";
			continue;
		}

		auto destPath = FS::PathCombine(m_stagingPath, "minecraft", mod.targetFolder, mod.name);
		if (mod.disabled)
			destPath += ".disabled";

		setStatus(tr("Copying Blocked Mods (%1 out of %2 are done)").arg(QString::number(i), QString::number(total)));

		qDebug() << "Will try to copy" << mod.localPath << "to" << destPath;

		if (mod.move)
		{
			if (!FS::move(mod.localPath, destPath))
			{
				qDebug() << "Move of" << mod.localPath << "to" << destPath << "Failed";
			}
		}
		else
		{
			if (!FS::copy(mod.localPath, destPath)())
			{
				qDebug() << "Copy of" << mod.localPath << "to" << destPath << "Failed";
			}
		}

		i++;
		setProgress(i, total);
	}

	setAbortable(true);
}

void FlameCreationTask::validateOtherResources(QEventLoop& loop)
{
	qDebug() << "Validating whether other resources are in the right place";
	QStringList zipMods;
	for (auto [fileName, targetFolder] : m_otherResources)
	{
		qDebug() << "Checking" << fileName << "...";
		auto localPath = FS::PathCombine(m_stagingPath, "minecraft", targetFolder, fileName);

		/// @brief check the target and move the the file
		/// @return path where file can now be found
		auto validatePath = [&localPath, this](QString fileName, QString targetFolder, QString realTarget)
		{
			if (targetFolder != realTarget)
			{
				qDebug() << "Target folder of" << fileName << "is incorrect, it belongs in" << realTarget;
				auto destPath = FS::PathCombine(m_stagingPath, "minecraft", realTarget, fileName);
				qDebug() << "Moving" << localPath << "to" << destPath;
				if (FS::move(localPath, destPath))
				{
					return destPath;
				}
			}
			else
			{
				qDebug() << "Target folder of" << fileName << "is correct at" << targetFolder;
			}
			return localPath;
		};

		auto installWorld = [this](QString worldPath)
		{
			qDebug() << "Installing World from" << worldPath;
			QFileInfo worldFileInfo(worldPath);
			World w(worldFileInfo);
			if (!w.isValid())
			{
				qDebug() << "World at" << worldPath << "is not valid, skipping install.";
			}
			else
			{
				w.install(FS::PathCombine(m_stagingPath, "minecraft", "saves"));
			}
		};

		QFileInfo localFileInfo(localPath);
		auto type = ResourceUtils::identify(localFileInfo);

		QString worldPath;

		switch (type)
		{
			case ModPlatform::ResourceType::Mod:
				validatePath(fileName, targetFolder, "mods");
				zipMods.push_back(fileName);
				break;
			case ModPlatform::ResourceType::ResourcePack: validatePath(fileName, targetFolder, "resourcepacks"); break;
			case ModPlatform::ResourceType::TexturePack: validatePath(fileName, targetFolder, "texturepacks"); break;
			case ModPlatform::ResourceType::DataPack: validatePath(fileName, targetFolder, "datapacks"); break;
			case ModPlatform::ResourceType::ShaderPack:
				// in theory flame API can't do this but who knows, that *may* change ?
				// better to handle it if it *does* occur in the future
				validatePath(fileName, targetFolder, "shaderpacks");
				break;
			case ModPlatform::ResourceType::World:
				worldPath = validatePath(fileName, targetFolder, "saves");
				installWorld(worldPath);
				break;
			case ModPlatform::ResourceType::Unknown:
			/* fallthrough */
			default:
				qDebug() << "Can't Identify" << fileName << "at" << localPath << ", leaving it where it is.";
				break;
		}
	}
	// Generic metadata creation for supported resource types
	auto task	 = makeShared<ConcurrentTask>("CreateModMetadata",
											  APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt());
	auto results = m_modIdResolver->getResults().files;

	for (auto file : results)
	{
		QString indexParent;
		switch (file.resourceType)
		{
			case ModPlatform::ResourceType::Mod:
				// Skip if it looks like a zip but wasn't identified as a mod (e.g. valid resource pack that got
				// confused, or invalid file)
				if (file.version.fileName.endsWith(".zip") && !zipMods.contains(file.version.fileName))
				{
					continue;
				}
				indexParent = "mods";
				break;
			case ModPlatform::ResourceType::ResourcePack: indexParent = "resourcepacks"; break;
			case ModPlatform::ResourceType::ShaderPack: indexParent = "shaderpacks"; break;
			default: continue;
		}

		auto folder = FS::PathCombine(m_stagingPath, "minecraft", indexParent, ".index");
		task->addTask(makeShared<LocalResourceUpdateTask>(folder, file.pack, file.version));
	}

	connect(task.get(), &Task::finished, &loop, &QEventLoop::quit);
	m_processUpdateFileInfoJob = task;
	task->start();
}