package ru.dbotthepony.mc.otm.datagen

import net.minecraft.tags.ItemTags
import net.minecraft.world.item.Items
import net.minecraftforge.common.Tags
import ru.dbotthepony.mc.otm.OverdriveThatMatters
import ru.dbotthepony.mc.otm.android.AndroidResearchDescriptions
import ru.dbotthepony.mc.otm.android.AndroidResearchResults
import ru.dbotthepony.mc.otm.android.AndroidResearchType
import ru.dbotthepony.mc.otm.client.render.ResearchIcons
import ru.dbotthepony.mc.otm.core.TextComponent
import ru.dbotthepony.mc.otm.core.TranslatableComponent
import ru.dbotthepony.mc.otm.datagen.lang.MatteryLanguageProvider
import ru.dbotthepony.mc.otm.registry.AndroidFeatures
import ru.dbotthepony.mc.otm.registry.MItemTags
import ru.dbotthepony.mc.otm.registry.MItems
import ru.dbotthepony.mc.otm.registry.MNames
import java.util.LinkedList
import java.util.function.Consumer

@Suppress("LocalVariableName")
fun addResearchData(serializer: Consumer<AndroidResearchType>, lang: MatteryLanguageProvider) {
	val AIR_BAGS = AndroidResearchType.Builder(modLocation(MNames.AIR_BAGS))
		.withExperience(18)
		.addFeatureResult(AndroidFeatures.AIR_BAGS)
		.withDescription()
		.withIcon(ResearchIcons.ICON_AIR_BAGS)
		.addItem(Tags.Items.GLASS_PANES, 6)
		.addItem(MItemTags.IRON_PLATES)
		.build()

	serializer.accept(AIR_BAGS)

	val IMPROVED_LIMBS = AndroidResearchType.Builder(modLocation(MNames.IMPROVED_LIMBS))
		.withExperience(20)
		.withDescription()
		.withIcon(ResearchIcons.ICON_LIMB_OVERCLOCKING)
		.addItem(MItemTags.TRITANIUM_PLATES, 3)
		.addItem(MItemTags.IRON_PLATES, 2)
		.addItem(MItemTags.GOLD_WIRES, 4)
		.addItem(MItems.ELECTROMAGNET, 4)
		.build()

	serializer.accept(IMPROVED_LIMBS)

	val STEP_ASSIST = AndroidResearchType.Builder(modLocation(MNames.STEP_ASSIST))
		.withExperience(24)
		.addFeatureResult(AndroidFeatures.STEP_ASSIST)
		.withDescription()
		.withIcon(ResearchIcons.ICON_STEP_ASSIST)
		.addPrerequisite(IMPROVED_LIMBS)
		.addItem(MItemTags.PISTONS, 2)
		.addItem(MItemTags.TRITANIUM_PLATES, 4)
		.addItem(MItemTags.COPPER_WIRES, 6)
		.build()

	serializer.accept(STEP_ASSIST)

	val EXTENDED_REACH = AndroidResearchType.Builder(modLocation(MNames.EXTENDED_REACH))
		.withExperience(40)
		.addFeatureResult(AndroidFeatures.EXTENDED_REACH)
		.addPrerequisite(IMPROVED_LIMBS)
		.withDescription()
		.withIcon(ResearchIcons.ICON_EXTENDED_REACH)
		.addItem(MItemTags.PISTONS, 2)
		.addItem(MItemTags.TRITANIUM_PLATES, 4)
		.addItem(MItemTags.GOLD_WIRES, 6)
		.addItem(MItems.QUANTUM_TRANSCEIVER)
		.build()

	serializer.accept(EXTENDED_REACH)

	val NIGHT_VISION = AndroidResearchType.Builder(modLocation(MNames.NIGHT_VISION))
		.withExperience(40)
		.withDescription()
		.withIcon(ResearchIcons.ICON_NIGHT_VISION)
		.addFeatureResult(AndroidFeatures.NIGHT_VISION)
		.addItem(Tags.Items.GLASS_PANES_COLORLESS, 4)
		.addItem(Tags.Items.DUSTS_REDSTONE, 4)
		.addItem(MItemTags.TRITANIUM_PLATES, 2)
		.addItem(MItems.ELECTRIC_PARTS, 3)
		.addItem(MItemTags.ADVANCED_CIRCUIT)
		.addItem(Items.ENDER_EYE, 2)
		.build()

	serializer.accept(NIGHT_VISION)

	val NANOBOTS = AndroidResearchType.Builder(modLocation(MNames.NANOBOTS))
		.withExperience(15)
		.withDescription()
		.withIcon(ResearchIcons.ICON_NANOBOTS)
		.build()

	serializer.accept(NANOBOTS)

	val NANOBOTS_ARMOR = AndroidResearchType.Builder(modLocation(MNames.NANOBOTS_ARMOR))
		.withExperience(25)
		.withDescription()
		.addPrerequisite(OverdriveThatMatters.loc(MNames.NANOBOTS))
		.addFeatureResult(OverdriveThatMatters.loc(MNames.NANOBOTS_ARMOR))
		.withIcon(ResearchIcons.ICON_ARMOR)
		.addBlocker(OverdriveThatMatters.loc(MNames.ATTACK_BOOST_1), optional = true)
		.addItem(MItemTags.TRITANIUM_PLATES, 4)
		.addItem(MItemTags.COPPER_WIRES, 8)
		.build()

	serializer.accept(NANOBOTS_ARMOR)

	val limbList = LinkedList<AndroidResearchType>()
	val regenList = LinkedList<AndroidResearchType>()
	val armorStrengthList = LinkedList<AndroidResearchType>()
	val armorSpeedList = LinkedList<AndroidResearchType>()
	val attackBoostList = LinkedList<AndroidResearchType>()

	for (i in 0 until 4) {
		limbList.add(run {
			val research = AndroidResearchType.Builder(modLocation(MNames.LIMB_OVERCLOCKING_LIST[i]))
				.withExperience(18 + i * 8)
				.withIconText(TextComponent((i + 1).toString()))
				.addPrerequisite(IMPROVED_LIMBS)
				.withIcon(ResearchIcons.ICON_LIMB_OVERCLOCKING)
				.withName(TranslatableComponent("android_research.overdrive_that_matters.limb_overclocking", i + 1))
				.withDescription(
					TranslatableComponent(
						"android_research.overdrive_that_matters.limb_overclocking.description",
						(i + 1) * 8,
						(i + 1) * 6
					)
				)
				.addItem(MItemTags.COPPER_WIRES, 4 + i * 2)

			if (i > 0) {
				research.addFeatureLevel(AndroidFeatures.LIMB_OVERCLOCKING)
				research.addPrerequisite(OverdriveThatMatters.loc(MNames.LIMB_OVERCLOCKING_LIST[i - 1]), optional = true)
				research.addItem(MItemTags.GOLD_WIRES, i * 2)
			} else {
				research.addFeatureResult(AndroidFeatures.LIMB_OVERCLOCKING)
			}

			research.build()
		})

		attackBoostList.add(run {
			val research = AndroidResearchType.Builder(modLocation(MNames.ATTACK_BOOST_LIST[i]))
				.withExperience(18 + i * 8)
				.withIconText(TextComponent((i + 1).toString()))
				.addPrerequisite(IMPROVED_LIMBS)
				.withIcon(ResearchIcons.ICON_ATTACK_BOOST)
				.withName(TranslatableComponent("android_research.overdrive_that_matters.attack_boost", i + 1))
				.withDescription(
					TranslatableComponent(
						"android_research.overdrive_that_matters.attack_boost.description",
						(i + 1) * 15
					)
				)
				.addBlocker(NANOBOTS_ARMOR)

			if (i > 0) {
				research.addFeatureLevel(AndroidFeatures.ATTACK_BOOST)
				research.addPrerequisite(OverdriveThatMatters.loc(MNames.ATTACK_BOOST_LIST[i - 1]), optional = true)
			} else {
				research.addFeatureResult(AndroidFeatures.ATTACK_BOOST)
			}

			research.build()
		})

		regenList.add(run {
			val research = AndroidResearchType.Builder(modLocation(MNames.NANOBOTS_REGENERATION_LIST[i]))
				.withExperience(20 + i * 6)
				.withIconText(TextComponent((i + 1).toString()))
				.withIcon(ResearchIcons.ICON_NANOBOTS)
				.withName(TranslatableComponent("android_research.overdrive_that_matters.nanobots_regeneration", i + 1))
				.withDescription(
					if (i > 0) TranslatableComponent("android_research.overdrive_that_matters.nanobots_regeneration.description_improve") else TranslatableComponent(
						"android_research.overdrive_that_matters.nanobots_regeneration.description"
					)
				)
				.addItem(MItems.MATTER_CAPACITOR_PARTS, 1)
				.addItem(Items.SUGAR, 2 + i * 2)
				.addItem(Tags.Items.DUSTS_REDSTONE, 2 + i * 2)

			if (i > 0) {
				research.addFeatureLevel(AndroidFeatures.NANOBOTS_REGENERATION)
				research.addPrerequisite(OverdriveThatMatters.loc(MNames.NANOBOTS_REGENERATION_LIST[i - 1]), optional = true)
			} else {
				research.addPrerequisite(OverdriveThatMatters.loc(MNames.NANOBOTS), optional = true)
				research.addFeatureResult(AndroidFeatures.NANOBOTS_REGENERATION)
			}

			research.build()
		})
	}

	for (i in 0 until 3) {
		val level = i + 1

		armorStrengthList.add(run {
			AndroidResearchType.Builder(modLocation(MNames.NANOBOTS_ARMOR_STRENGTH_LIST[i]))
				.withExperience(20 + i * 8)
				.withIconText(TextComponent((i + 1).toString()))
				.withIcon(ResearchIcons.ICON_ARMOR)
				.addPrerequisite(OverdriveThatMatters.loc(if (i > 0) MNames.NANOBOTS_ARMOR_STRENGTH_LIST[i - 1] else MNames.NANOBOTS_ARMOR))
				.withName(
					TranslatableComponent(
						"android_research.overdrive_that_matters.nanobots_armor_strength",
						i + 1
					)
				)
				.withDescription(
					TranslatableComponent(
						"android_research.overdrive_that_matters.nanobots_armor_strength.description",
						(i + 1) * 8,
						(i + 1) * 6
					)
				)
				.addItem(MItemTags.TRITANIUM_PLATES, 2 + i * 2)
				.addItem(Items.SUGAR, 1 + i)
				.addItem(MItems.ELECTROMAGNET)
				.addResult(AndroidResearchResults.NANOBOTS_ARMOR_STRENGTH)
				.build()
		})

		armorSpeedList.add(run {
			AndroidResearchType.Builder(modLocation(MNames.NANOBOTS_ARMOR_SPEED_LIST[i]))
				.withExperience(18 + i * 6)
				.withIconText(TextComponent((i + 1).toString()))
				.withIcon(ResearchIcons.ICON_ARMOR)
				.addPrerequisite(OverdriveThatMatters.loc(if (i > 0) MNames.NANOBOTS_ARMOR_SPEED_LIST[i - 1] else MNames.NANOBOTS_ARMOR))
				.withName(
					TranslatableComponent(
						"android_research.overdrive_that_matters.nanobots_armor_speed",
						i + 1
					)
				)
				.withDescription(
					TranslatableComponent(
						"android_research.overdrive_that_matters.nanobots_armor_speed.description",
						(i + 1) * 8,
						(i + 1) * 6
					)
				)
				.addItem(Tags.Items.DUSTS_REDSTONE, 4 + i * 4)
				.addResult(AndroidResearchResults.NANOBOTS_ARMOR_SPEED)
				.build()
		})
	}

	limbList.forEach(serializer::accept)
	regenList.forEach(serializer::accept)
	armorStrengthList.forEach(serializer::accept)
	armorSpeedList.forEach(serializer::accept)
	attackBoostList.forEach(serializer::accept)

	val SHOCKWAVE =
		AndroidResearchType.Builder(modLocation(MNames.SHOCKWAVE))
			.withExperience(40)
			.withDescription(0 .. 1)
			.withDescription(AndroidResearchDescriptions.SHOCKWAVE)
			.withIcon(ResearchIcons.ICON_SHOCKWAVE)
			.addFeatureResult(AndroidFeatures.SHOCKWAVE)
			.addPrerequisite(attackBoostList[2])
			.addItem(Tags.Items.ENDER_PEARLS)
			.addItem(Tags.Items.DUSTS_REDSTONE, 2)
			.addItem(MItemTags.GOLD_WIRES, 4)
			.addItem(MItemTags.GOLD_PLATES, 2)
			.addItem(MItems.ELECTROMAGNET, 2)
			.build()

	val ITEM_MAGNET =
		AndroidResearchType.Builder(modLocation(MNames.ITEM_MAGNET))
			.withExperience(28)
			.withDescription(0 .. 1)
			.withDescription(AndroidResearchDescriptions.ITEM_MAGNET)
			.withIcon(ResearchIcons.ICON_ITEM_MAGNET)
			.addFeatureResult(AndroidFeatures.ITEM_MAGNET)
			.addPrerequisite(STEP_ASSIST)
			.addItem(MItems.QUANTUM_TRANSCEIVER)
			.addItem(Tags.Items.DUSTS_REDSTONE, 4)
			.addItem(MItems.ELECTROMAGNET, 4)
			.build()

	serializer.accept(SHOCKWAVE)
	serializer.accept(ITEM_MAGNET)

	val FALL_DAMPENERS_1 =
		AndroidResearchType.Builder(modLocation(MNames.FALL_DAMPENERS + "_1"))
			.withExperience(25)
			.withDescription()
			.withDescription(AndroidResearchDescriptions.FALL_DAMPENERS.Instance(1))
			.withIcon(ResearchIcons.ICON_FEATHER_FALLING)
			.addFeatureResult(AndroidFeatures.FALL_DAMPENERS)
			.addPrerequisite(STEP_ASSIST)
			.addItem(MItems.ELECTROMAGNET, 2)
			.addItem(ItemTags.WOOL, 2)
			.withIconText(TextComponent("1"))
			.build()

	val FALL_DAMPENERS_2 =
		AndroidResearchType.Builder(modLocation(MNames.FALL_DAMPENERS + "_2"))
			.withExperience(30)
			.withDescription()
			.withDescription(AndroidResearchDescriptions.FALL_DAMPENERS.Instance(2))
			.withIcon(ResearchIcons.ICON_FEATHER_FALLING)
			.addFeatureLevel(AndroidFeatures.FALL_DAMPENERS)
			.addPrerequisite(FALL_DAMPENERS_1)
			.addItem(MItemTags.GOLD_PLATES, 2)
			.addItem(MItemTags.COPPER_WIRES, 4)
			.addItem(Tags.Items.SLIMEBALLS, 4)
			.withIconText(TextComponent("2"))
			.build()

	val FALL_DAMPENERS_3 =
		AndroidResearchType.Builder(modLocation(MNames.FALL_DAMPENERS + "_3"))
			.withExperience(35)
			.withDescription(0 .. 1)
			.withDescription(AndroidResearchDescriptions.FALL_DAMPENERS.Instance(3))
			.withIcon(ResearchIcons.ICON_FEATHER_FALLING)
			.addFeatureLevel(AndroidFeatures.FALL_DAMPENERS)
			.addPrerequisite(FALL_DAMPENERS_2)
			.addItem(MItemTags.ADVANCED_CIRCUIT, 2)
			.addItem(Tags.Items.GEMS_DIAMOND, 4)
			.addItem(Tags.Items.ENDER_PEARLS, 2)
			.withIconText(TextComponent("3"))
			.build()

	serializer.accept(FALL_DAMPENERS_1)
	serializer.accept(FALL_DAMPENERS_2)
	serializer.accept(FALL_DAMPENERS_3)

	val ENDER_TELEPORTER =
		AndroidResearchType.Builder(modLocation(MNames.ENDER_TELEPORTER))
			.withExperience(35)
			.withDescription()
			.withDescription(AndroidResearchDescriptions.ENDER_TELEPORTER)
			.withIcon(ResearchIcons.ICON_ENDER_TELEPORT)
			.addFeatureResult(AndroidFeatures.ENDER_TELEPORTER)
			.addPrerequisite(FALL_DAMPENERS_1)
			.addItem(MItemTags.ADVANCED_CIRCUIT, 4)
			.addItem(MItems.ELECTROMAGNET, 4)
			.addItem(MItems.ELECTRIC_PARTS, 4)
			.addItem(Tags.Items.ENDER_PEARLS, 4)
			.addItem(Tags.Items.GEMS_EMERALD, 2)
			.build()

	serializer.accept(ENDER_TELEPORTER)

	val JUMP_BOOST_1 =
		AndroidResearchType.Builder(modLocation(MNames.JUMP_BOOST + "_1"))
			.withExperience(27)
			.withDescription(0 .. 1)
			.withDescription(AndroidResearchDescriptions.JUMP_BOOST)
			.withIcon(ResearchIcons.ICON_JUMP_BOOST)
			.addFeatureResult(AndroidFeatures.JUMP_BOOST)
			.addItem(MItemTags.PISTONS, 2)
			.addItem(MItemTags.GOLD_WIRES, 4)
			.addItem(MItems.ELECTROMAGNET, 2)
			.withIconText(TextComponent("1"))
			.addPrerequisite(FALL_DAMPENERS_1)
			.build()

	val JUMP_BOOST_2 =
		AndroidResearchType.Builder(modLocation(MNames.JUMP_BOOST + "_2"))
			.withExperience(34)
			.withDescription()
			.withDescription(AndroidResearchDescriptions.JUMP_BOOST)
			.withIcon(ResearchIcons.ICON_JUMP_BOOST)
			.addFeatureLevel(AndroidFeatures.JUMP_BOOST)
			.addItem(MItems.ELECTRIC_PARTS, 4)
			.addItem(MItems.ELECTROMAGNET, 4)
			.addPrerequisite(JUMP_BOOST_1)
			.withIconText(TextComponent("2"))
			.build()

	serializer.accept(JUMP_BOOST_1)
	serializer.accept(JUMP_BOOST_2)

	with(lang) {
		misc("fall_dampeners.description", "Reduces fall damage by %s%% and increases fall damage flat resist by %s half a hearts") {
			russian("Уменьшает урон от падения на %s%% и повышает сопротивление урону от падения на %s полусердец")
		}

		add(limbList[0], "Limb Overclocking %s") {
			russian("Разгон Конечностей %s")
		}

		add(limbList[0], "description", "Boosts mobility by %s%% and attack speed by %s%%") {
			russian("Увеличивает мобильность на %s%% и скорость атак на %s%%")
		}

		add(AIR_BAGS, "Air Bags") {
			russian("Воздушные Мешки")
		}
		add(NANOBOTS, "Nanobots") {
			russian("Наноботы")
		}
		add(AIR_BAGS, "description", "Allows to swim in water") {
			russian("Позволяет плавать в воде")
		}
		add(NANOBOTS, "description", "Various useful nanobots for doing various tasks") {
			russian("Различные наноботы для различных задач")
		}

		add(regenList[0], "Regeneration %s") {
			russian("Регенерация %s")
		}
		add(regenList[0], "description", "Nanobots get ability to repair internal Android' systems on the move") {
			russian("Наноботы получают возможность чинить внутренние системы Андроида на ходу")
		}
		add(regenList[0], "description_improve", "Improves health regeneration speed") {
			russian("Улучшает скорость регенерации здоровья")
		}

		add(NANOBOTS_ARMOR, "Nanobots Armor") {
			russian("Броня из Наноботов")
		}
		add(NANOBOTS_ARMOR, "description", "Allows nanobots to align themselves in cell shape, reducing incoming damage by a %% by absorbing impacts") {
			russian("Позволяет наноботам выстраиваться в клеточную структуру, уменьшая внешний урон на определённый проект путём поглощения ударов")
		}

		add(armorSpeedList[0], "Nanobots Armor Build Speed %s") {
			russian("Скорость Построения Слоя Брони Наноботов %s")
		}
		add(armorSpeedList[0], "description", "Reduces time required for nanobots to form protection layer") {
			russian("Уменьшает время необходимое наноботам для формирования защитного слоя")
		}

		add(armorStrengthList[0], "Nanobots Armor Strength %s") {
			russian("Сила Слоя Брони Наноботов %s")
		}
		add(armorStrengthList[0], "description", "Increases impact absorption strength of nanobots") {
			russian("Увеличивает поглощающею силу брони наноботов")
		}

		add(EXTENDED_REACH, "Extended Reach") {
			russian("Удлинённые Манипуляторы")
		}
		add(EXTENDED_REACH, "description", "Increases block interaction distance") {
			russian("Увеличивает радиус взаимодействия с блоками")
		}

		add(IMPROVED_LIMBS, "Improved Limbs") {
			russian("Улучшенные Конечности")
		}
		add(IMPROVED_LIMBS, "description", "Allows limbs to be upgraded") {
			russian("Позволяет улучшать конечности")
		}

		add(STEP_ASSIST, "Step Assist") {
			russian("Помощь Подъёма")
		}
		add(STEP_ASSIST, "description", "Allows unit to step up whole blocks") {
			russian("Позволяет переступать полные блоки")
		}

		add(ITEM_MAGNET, "Item Magnet") {
			russian("Предметный Магнит")
		}
		add(ITEM_MAGNET, "description0", "Pulls nearby items while active") {
			russian("Притягивает ближайшие предметы пока активен")
		}
		add(ITEM_MAGNET, "description1", "Drains energy for each item stack it pulls") {
			russian("Потребляет энергию за каждую стопку которую притягивает магнит")
		}

		add(FALL_DAMPENERS_1, "Fall Dampeners") {
			russian("Поглотители Инерции")
		}
		add(FALL_DAMPENERS_1, "description", "Installs basic equipment in limbs to negate some fall damage") {
			russian("Обустраивает конечности примитивными деталями для небольшого смягчения падения")
		}

		add(FALL_DAMPENERS_2, "Fall Dampeners 2") {
			russian("Поглотители Инерции 2")
		}
		add(FALL_DAMPENERS_2, "description", "Installs micro displacing and dampening equipment in limbs to negate great deal of fall damage") {
			russian("Оборудует конечности микро смещающимися и смягчающим оборудованием, которое поглощает значительный урон от падения")
		}

		add(FALL_DAMPENERS_3, "Fall Dampeners 3") {
			russian("Поглотители Инерции 3")
		}
		add(FALL_DAMPENERS_3, "description0", "Installs autonomous fall damage avoidance calculation matrices and hardening to crucial parts") {
			russian("Устанавливает автономные матрицы калькуляции избегания урона от падения, а так же усиливает защиту важных деталей")
		}
		add(FALL_DAMPENERS_3, "description1", "of limbs to land on to negate most of fall damage") {
			russian("от урона от падения для почти полного поглощения урона от падения")
		}

		add(SHOCKWAVE, "Shockwave Pulsator") {
			russian("Генератор Ударных Волн")
		}
		add(SHOCKWAVE, "description0", "Releases a shockwave, damaging everything in small radius, as you quickly land on ground") {
			russian("Вызывает ударную волну при стремительном падении на землю, нанося урон всему, что вас окружает")
		}
		add(SHOCKWAVE, "description1", "It does not, however, help with ground impact damage!") {
			russian("Используйте с осторожностью, так как данная технология сама по себе не поглащает урон от падения!")
		}

		add(JUMP_BOOST_1, "Jump Boost") {
			russian("Усилитель Прыжка")
		}
		add(JUMP_BOOST_1, "description0", "Allows to perform higher jump") {
			russian("Позволяет совершить высокий прыжок")
		}
		add(JUMP_BOOST_1, "description1", "Can be activated by crouching and jumping at the same time") {
			russian("Для прыжка удерживайте кнопку приседания и нажмите кнопку прыжка")
		}

		add(JUMP_BOOST_2, "Jump Boost 2") {
			russian("Усилитель Прыжка 2")
		}
		add(JUMP_BOOST_2, "description", "Allows to perform extra higher jump") {
			russian("Позволяет совершить ещё более высокий прыжок")
		}

		add(ENDER_TELEPORTER, "Ender Teleporter") {
			russian("Телепортатор Края")
		}
		add(ENDER_TELEPORTER, "description", "Allows to perform instant, short distance teleports without damage to internal systems") {
			russian("Позволяет совершать мгновенную телепортацию на короткую дистанцию без нанесения урона внутренним системам")
		}

		add(NIGHT_VISION, "Night Vision") {
			russian("Ночное Зрение")
		}
		add(NIGHT_VISION, "description", "Allows to clearly see in the dark") {
			russian("Позволяет видеть в темноте")
		}

		add(attackBoostList[0], "Attack Boost %s") {
			russian("Усиление Атаки %s")
		}
		add(attackBoostList[0], "description", "Increases total melee attack strength by %s%%") {
			russian("Увеличивает урон в ближнем бою на %s%%")
		}
	}
}
