 using HarmonyLib;
using NCMS;
using ReflectionUtility;
using System.Collections.Generic;
using System.Linq;
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using UnityEngine;
using UnityEngine.Purchasing.MiniJSON;
using Cultivation_Way;
using Cultivation_Way.Utils;
using Cultivation_Way.Others;
using Cultivation_Way.Library;
using Cultivation_Way.Actions;
using Cultivation_Way.Animation;
using static Config;

namespace CW_trait
{
    [ModEntry]
    class Main : CW_Addon
    {
		private static CW_Asset_CultiSys yuan;
		private static CW_Asset_CultiSys tianqian;
		public override void awake(){
			// 不要在此处添加代码，除非你知道你在做什么
			// DO NOT code here.
			load_mod_info(System.Type.GetType("Mod"));
		}
		public override void initialize(){
			Log("添加元寿道");
			// 在这里初始化模组内容
			// Initalize your mod content here
			add_example_trait();
			Harmony.CreateAndPatchAll(typeof(Main), "CW_Addon_yuan");
			add_yuan_cultisys();
			add_yuan_combo_status();
			Harmony.CreateAndPatchAll(typeof(Main), "CW_Addon_tianqian");
			add_tianqian_cultisys();
			add_tiansha_trait();
			add_tianqian_trait();
		}
		
		private void add_example_trait(){
			// 原版特质
			ActorTrait origin = new ActorTrait();
			origin.id = "spelleternalfour";
			origin.path_icon = "Icons/icondfwd";
			origin.needs_to_be_explored = false;
			origin.birth = 10f;
			origin.inherit = 10f;
			CW_Asset_Trait spelleternalfour = new CW_Asset_Trait();
			// 包装原版特质，即将提供更简单的创建与包装方式
			spelleternalfour.id = origin.id;
			spelleternalfour.origin_asset = origin;
			spelleternalfour.addition_stats = new CW_BaseStats();
			spelleternalfour.addition_stats.base_stats = origin.baseStats;
			spelleternalfour.addition_stats.wakan_regen = 9;
			// 设置修炼速度加成72%
			spelleternalfour.addition_stats.mod_wakan_regen = 108f;
			// 设置灵力上限系数加成108%
			spelleternalfour.addition_stats.mod_wakan = 72f;
			// 添加
            CW_Library_Manager.instance.traits.add(spelleternalfour);
		}

		private void add_tiansha_trait(){
			// 原版特质
			ActorTrait origin = new ActorTrait();
			origin.id = "tiansha";
			origin.path_icon = "Icons/icontiansha";
			origin.needs_to_be_explored = false;
			origin.birth = 0f;
			origin.inherit = 0f;
			origin.baseStats.mod_health = 100f;
			origin.baseStats.damage = 500;
			CW_Asset_Trait tiansha = new CW_Asset_Trait();
			// 包装原版特质，即将提供更简单的创建与包装方式
			tiansha.id = origin.id;
			tiansha.origin_asset = origin;
			tiansha.addition_stats = new CW_BaseStats();
			tiansha.addition_stats.base_stats = origin.baseStats;
			tiansha.addition_stats.wakan_regen = 9;
			// 设置修炼速度加成72%
			tiansha.addition_stats.mod_wakan_regen = 108f;
			// 设置灵力上限系数加成108%
			tiansha.addition_stats.mod_wakan = 72f;
			// 添加
            CW_Library_Manager.instance.traits.add(tiansha);
		}

		private void add_tianqian_trait(){
			// 原版特质
			ActorTrait origin = new ActorTrait();
			origin.id = "tianqian";
			origin.path_icon = "Icons/icondfwdsi";
			origin.needs_to_be_explored = false;
			origin.birth = 1f;
			origin.inherit = 20f;
			origin.baseStats.mod_damage = -32f;
			origin.baseStats.mod_armor = -70f;
			origin.baseStats.mod_health = -70f;
			CW_Asset_Trait tianqian = new CW_Asset_Trait();
			// 包装原版特质，即将提供更简单的创建与包装方式
			tianqian.id = origin.id;
			tianqian.origin_asset = origin;
			tianqian.addition_stats = new CW_BaseStats();
			tianqian.addition_stats.mod_cultivation = -1000f;
			tianqian.addition_stats.mod_wakan_regen = -100f;
			tianqian.addition_stats.mod_health_regen = -99f;
			tianqian.addition_stats.mod_age = -72f;
			tianqian.addition_stats.mod_soul = 10000f;
			tianqian.addition_stats.mod_wakan = -500f;
			tianqian.addition_stats.mod_anti_armor = -5000f;
			tianqian.addition_stats.mod_anti_spell_armor = 1000f;
			tianqian.addition_stats.spell_armor = 100000;
			tianqian.addition_stats.mod_soul_regen = 200f;
			tianqian.addition_stats.mod_anti_crit_damage = 1000f;
			tianqian.addition_stats.vampire = 100;
			tianqian.addition_stats.base_stats = origin.baseStats;
			// 添加
            CW_Library_Manager.instance.traits.add(tianqian);
		}

		private void add_yuan_combo_status()
        {
            CW_BaseStats bonus_stats = new CW_BaseStats();
            CW_Asset_StatusEffect status_effect = new CW_Asset_StatusEffect(
                id: "status_yuan_combo",
                anim_id: "status_fen_fire_anim",
                bonus_stats: bonus_stats,
                effect_val: 5,
                effect_time: 5f,
                action_on_get: bcopy_bonus_stats_on_get,
                action_on_update: yuan_combo_update_action,
                action_on_end: null
                );
            CW_Library_Manager.instance.status_effects.add(status_effect);
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(Actor), "newKillAction")]
		public static void yuan_bonus(Actor __instance, Actor pDeadUnit)
        {
			CW_Actor actor = (CW_Actor)__instance;
			if (!actor.has_cultisys(yuan.id))
            {
				if(actor.fast_data.age >= 500)
                {
					actor.add_cultisys(yuan.id);
                }
				return;
            }
			actor.regen_health(((CW_Actor)pDeadUnit).cw_cur_stats.health_regen);
			actor.regen_wakan(((CW_Actor)pDeadUnit).cw_cur_stats.wakan_regen);
			CW_BaseStats cw_stats = actor.get_fixed_base_stats();
			cw_stats.base_stats.mod_health += 0.01f;
			cw_stats.base_stats.mod_damage += 0.09f;
			cw_stats.base_stats.mod_armor += 0.01f;
			cw_stats.base_stats.mod_attackSpeed += 0.01f;
			cw_stats.mod_spell_armor += 0.1f;
			cw_stats.mod_wakan += 1f;
			cw_stats.mod_wakan_regen += 0.5f;
			cw_stats.mod_shield_regen += 0.1f;
			cw_stats.mod_shield += 0.1f;
			cw_stats.age_bonus++;
			cw_stats.mod_shield += 0.1f;
			cw_stats.mod_age -= 0.001f;
			actor.clear_default_spell_timer();
            if (CW_Actor.get_attackTarget(actor) == null)
            {
				List<BaseSimObject> enemies = CW_SpellHelper.find_enemies_in_square(actor.currentTile, actor.kingdom, 8);
				foreach(BaseSimObject enemy in enemies)
                {
					if (enemy.objectType == MapObjectType.Building) continue;
					CW_Actor.set_attackedBy(actor, enemy);
					actor.try_to_set_attack_target_by_attacked_by();
					break;
                }
            }
			add_or_enpower_yuan_combo((CW_Actor)actor);
			actor.setStatsDirty();
			actor.check_level_up();
        }
		private static void bcopy_bonus_stats_on_get(CW_StatusEffectData status_effect, BaseSimObject _obejct)
        {
            status_effect.bonus_stats = status_effect.bonus_stats.deepcopy();
        }
		
		private static void yuan_combo_update_action(CW_StatusEffectData status_effect, BaseSimObject _object)
        {
            if (_object.objectType != MapObjectType.Actor) return;
            for(int i=0;i<10;i++)((CW_Actor)_object).spawnParticle(Color.red);
        }
		
		private static void add_or_enpower_yuan_combo(CW_Actor actor)
		{
			CW_StatusEffectData combo_status_effect = actor.add_status_effect("status_yuan_combo", "status_yuan_combo");
			combo_status_effect.next_update_action_time = 0;
			
			combo_status_effect.bonus_stats.base_stats.damage += (int)UnityEngine.Mathf.Sqrt(actor.fast_data.age);
			CW_BaseStats cw_stats = combo_status_effect.bonus_stats;
			cw_stats.base_stats.mod_health += 5f;
			cw_stats.base_stats.mod_damage += 5f;
			cw_stats.base_stats.mod_armor += 10f;
			cw_stats.base_stats.mod_attackSpeed += 20f;
			cw_stats.mod_spell_armor += 20f;
			cw_stats.mod_wakan += 20f;
			cw_stats.mod_wakan_regen += 50f;
			cw_stats.mod_shield_regen += 20f;
			cw_stats.mod_shield += 10f;
			cw_stats.mod_age -= 0.00001f;
			
			combo_status_effect.left_time = combo_status_effect.left_time>combo_status_effect.status_asset.effect_val?combo_status_effect.left_time:combo_status_effect.status_asset.effect_val;
		}
		private void add_yuan_cultisys(){
			yuan = CW_Library_Manager.instance.cultisys.add(
				new CW_Asset_CultiSys()
				{
					id = "yuan",
					sprite_name = "iconCultiBook_Immortal",
					judge = yuan_judge,
					level_judge = yuan_level_judge,
					addition_spell_require = new CW_Spell_Tag[] { CW_Spell_Tag.IMMORTAL, CW_Spell_Tag.ACQUIRED_POWER }
				}
			);
			CW_Asset_CultiSys immortal = CW_Library_Manager.instance.cultisys.get("immortal");
			for (int i = 0; i < CW_Constants.max_cultisys_level; i++)
            {
				yuan.power_level[i] = 1 + i / (2f*CW_Constants.max_cultisys_level);
				yuan.bonus_stats[i] = immortal.bonus_stats[i].deepcopy();
				yuan.bonus_stats[i].wakan = 100*i;
				yuan.bonus_stats[i].wakan_regen /= 100;
				yuan.bonus_stats[i].base_stats.damage *= yuan.bonus_stats[i].base_stats.damage;
				yuan.bonus_stats[i].age_bonus /= 10;
			}
			yuan.races_list.Add("elf");
		}
		private static bool yuan_judge(CW_Actor cw_actor, CW_Asset_CultiSys cultisys)
        {
			return cw_actor.haveTrait("spelleternalfour") || cw_actor.haveTrait("Youss");
        }
		private static bool yuan_level_judge(CW_Actor cw_actor, CW_Asset_CultiSys cultisys)
        {
            if (cw_actor.cw_data.cultisys_level[cultisys.tag] <= CW_Constants.max_cultisys_level - 1 - 1 && cw_actor.fast_data.age >= cw_actor.cw_data.cultisys_level[cultisys.tag] *5* cw_actor.cw_data.cultisys_level[cultisys.tag])
			{
				if (cw_actor.city != null)
                {

                }
                else if(Toolbox.randomChance(1-5f / (10+cw_actor.cw_data.cultisys_level[cultisys.tag])))
                {
					cw_actor.addTrait("dfwdwu");
                }
				if (cw_actor.cw_status.health_level < cultisys.power_level[cw_actor.cw_data.cultisys_level[cultisys.tag] + 1])
				{
					cw_actor.fast_data.health = (int)CW_Utils_Others.get_raw_wakan(cw_actor.fast_data.health, cw_actor.cw_status.health_level);

					cw_actor.cw_status.health_level = cultisys.power_level[cw_actor.cw_data.cultisys_level[cultisys.tag] + 1];

					cw_actor.fast_data.health = (int)CW_Utils_Others.compress_raw_wakan(cw_actor.fast_data.health, cw_actor.cw_status.health_level);
				}
				if (cw_actor.cw_status.wakan_level < cultisys.power_level[cw_actor.cw_data.cultisys_level[cultisys.tag] + 1])
				{
					cw_actor.cw_status.wakan = (int)CW_Utils_Others.get_raw_wakan(cw_actor.cw_status.wakan, cw_actor.cw_status.wakan_level);

					cw_actor.cw_status.wakan_level = cultisys.power_level[cw_actor.cw_data.cultisys_level[cultisys.tag] + 1];

					cw_actor.cw_status.wakan = (int)CW_Utils_Others.compress_raw_wakan(cw_actor.cw_status.wakan, cw_actor.cw_status.wakan_level);
				}
				return true;
			}
			return false;
		}
		
		private void add_tianqian_combo_status()
        {
            CW_BaseStats bonus_stats = new CW_BaseStats();
            CW_Asset_StatusEffect status_effect = new CW_Asset_StatusEffect(
                id: "status_tianqian_combo",
                anim_id: "status_curse",
                bonus_stats: bonus_stats,
                effect_val: 5,
                effect_time: 5f,
                action_on_get: acopy_bonus_stats_on_get,
                action_on_update: tianqian_combo_update_action,
                action_on_end: null
                );
            CW_Library_Manager.instance.status_effects.add(status_effect);
        }

        [HarmonyPostfix]
        [HarmonyPatch(typeof(Actor), "newKillAction")]
		public static void tianqian_bonus(Actor __instance, Actor pDeadUnit)
        {
			CW_Actor actor = (CW_Actor)__instance;
			if (!actor.has_cultisys(tianqian.id))
            {
				if(actor.fast_data.age >= 9999)
                {
					actor.add_cultisys(tianqian.id);
                }
				return;
            }
			actor.regen_health(((CW_Actor)pDeadUnit).cw_cur_stats.health_regen);
			actor.regen_wakan(((CW_Actor)pDeadUnit).cw_cur_stats.wakan_regen);
			CW_BaseStats cw_stats = actor.get_fixed_base_stats();
			cw_stats.base_stats.mod_health += 0.1f;
			cw_stats.base_stats.mod_damage += 0.1f;
			cw_stats.base_stats.mod_armor += 0.1f;
			cw_stats.base_stats.mod_attackSpeed += 0.1f;
			cw_stats.mod_spell_armor += 0.1f;
			cw_stats.mod_wakan += 0.1f;
			cw_stats.mod_wakan_regen += 0.1f;
			cw_stats.mod_shield_regen += 0.1f;
			cw_stats.age_bonus++;
			cw_stats.mod_shield += 0.1f;
			cw_stats.mod_age -= 0.0001f;
			actor.clear_default_spell_timer();
            if (CW_Actor.get_attackTarget(actor) == null)
            {
				List<BaseSimObject> enemies = CW_SpellHelper.find_enemies_in_square(actor.currentTile, actor.kingdom, 8);
				foreach(BaseSimObject enemy in enemies)
                {
					if (enemy.objectType == MapObjectType.Building) continue;
					CW_Actor.set_attackedBy(actor, enemy);
					actor.try_to_set_attack_target_by_attacked_by();
					break;
                }
            }
			add_or_enpower_tianqian_combo((CW_Actor)actor);
			actor.setStatsDirty();
			actor.check_level_up();
        }
		private static void acopy_bonus_stats_on_get(CW_StatusEffectData status_effect, BaseSimObject _obejct)
        {
            status_effect.bonus_stats = status_effect.bonus_stats.deepcopy();
        }
		
		private static void tianqian_combo_update_action(CW_StatusEffectData status_effect, BaseSimObject _object)
        {
            if (_object.objectType != MapObjectType.Actor) return;
            for(int i=0;i<10;i++)((CW_Actor)_object).spawnParticle(Color.red);
        }
		
		private static void add_or_enpower_tianqian_combo(CW_Actor actor)
		{
			CW_StatusEffectData combo_status_effect = actor.add_status_effect("status_tianqian_combo", "status_tianqian_combo");
			combo_status_effect.next_update_action_time = 0;
			
			combo_status_effect.bonus_stats.base_stats.damage += (int)UnityEngine.Mathf.Sqrt(actor.fast_data.age);
			CW_BaseStats cw_stats = combo_status_effect.bonus_stats;
			cw_stats.base_stats.mod_health += 0.1f;
			cw_stats.base_stats.mod_damage += 15f;
			cw_stats.base_stats.mod_armor += 0.001f;
			cw_stats.base_stats.mod_attackSpeed += 5f;
			cw_stats.mod_spell_armor += 10f;
			cw_stats.mod_wakan += 10f;
			cw_stats.mod_wakan_regen += 10f;
			cw_stats.mod_shield_regen += 10f;
			cw_stats.mod_shield += 5f;
			cw_stats.mod_age -= 0.001f;
			
			combo_status_effect.left_time = combo_status_effect.left_time>combo_status_effect.status_asset.effect_val?combo_status_effect.left_time:combo_status_effect.status_asset.effect_val;
		}
		private void add_tianqian_cultisys(){
			tianqian = CW_Library_Manager.instance.cultisys.add(
				new CW_Asset_CultiSys()
				{
					id = "tianqian",
					sprite_name = "iconCultiBook_Immortal",
					judge = tianqian_judge,
					level_judge = tianqian_level_judge,
					addition_spell_require = new CW_Spell_Tag[] { CW_Spell_Tag.IMMORTAL, CW_Spell_Tag.ACQUIRED_POWER }
				}
			);
			CW_Asset_CultiSys immortal = CW_Library_Manager.instance.cultisys.get("immortal");
			for (int i = 0; i < CW_Constants.max_cultisys_level; i++)
            {
				tianqian.power_level[i] = 1 + i / (2f*CW_Constants.max_cultisys_level);
				tianqian.bonus_stats[i] = immortal.bonus_stats[i].deepcopy();
				tianqian.bonus_stats[i].wakan = 1000*i;
				tianqian.bonus_stats[i].wakan_regen /= 100;
				tianqian.bonus_stats[i].base_stats.damage *= tianqian.bonus_stats[i].base_stats.damage;
				tianqian.bonus_stats[i].age_bonus /= 10;
			}
			tianqian.races_list.Add("elf");
		}
		private static bool tianqian_judge(CW_Actor cw_actor, CW_Asset_CultiSys cultisys)
        {
			return cw_actor.haveTrait("tianqian") || cw_actor.haveTrait("yuwudi");
        }
		private static bool tianqian_level_judge(CW_Actor cw_actor, CW_Asset_CultiSys cultisys)
        {
            if (cw_actor.cw_data.cultisys_level[cultisys.tag] <= CW_Constants.max_cultisys_level - 1 - 1 && cw_actor.fast_data.kills >= cw_actor.cw_data.cultisys_level[cultisys.tag] *10* cw_actor.cw_data.cultisys_level[cultisys.tag])
			{
				if (cw_actor.city != null)
                {

                }
                else if(Toolbox.randomChance(99f / (10+cw_actor.cw_data.cultisys_level[cultisys.tag])))
                {
					cw_actor.addTrait("madness");
					cw_actor.addTrait("tiansha");
					cw_actor.addTrait("tianqian");
                }
				if (cw_actor.cw_status.health_level < cultisys.power_level[cw_actor.cw_data.cultisys_level[cultisys.tag] + 1])
				{
					cw_actor.fast_data.health = (int)CW_Utils_Others.get_raw_wakan(cw_actor.fast_data.health, cw_actor.cw_status.health_level);

					cw_actor.cw_status.health_level = cultisys.power_level[cw_actor.cw_data.cultisys_level[cultisys.tag] + 1];

					cw_actor.fast_data.health = (int)CW_Utils_Others.compress_raw_wakan(cw_actor.fast_data.health, cw_actor.cw_status.health_level);
				}
				if (cw_actor.cw_status.wakan_level < cultisys.power_level[cw_actor.cw_data.cultisys_level[cultisys.tag] + 1])
				{
					cw_actor.cw_status.wakan = (int)CW_Utils_Others.get_raw_wakan(cw_actor.cw_status.wakan, cw_actor.cw_status.wakan_level);

					cw_actor.cw_status.wakan_level = cultisys.power_level[cw_actor.cw_data.cultisys_level[cultisys.tag] + 1];

					cw_actor.cw_status.wakan = (int)CW_Utils_Others.compress_raw_wakan(cw_actor.cw_status.wakan, cw_actor.cw_status.wakan_level);
				}
				return true;
			}
			return false;
		}
    }
}