using System;
using UnityEngine;
using VOID.Generic.Dict;
using VOID.Generic.Objects.Wearable.Events;
using Object = UnityEngine.Object;

namespace VOID.Generic.Objects.Weapon
{
    [Serializable]
    public class WeaponObjectState : ObjectComponent<WeaponObject>
    {
        #region Initialize

        protected override void EventInitialize()
        {
            parent.wearableEvents.onEquippedAfter.AddListener(ShowEquipModel);
            parent.wearableEvents.onUnEquippedAfter.AddListener(HideEquipModel);
        }

        #endregion

        public GameObject equippedModel { get; private set; }
        public GameObject equippedModelHandIK { get; private set; }

        private void ShowEquipModel(EquipEvent equipEvent)
        {
            // Point (aka bone) where weapon's model will be attached 
            var equipPoint = equipEvent.slotType switch
            {
                EquipmentSlotType.MainHand when parent.weaponData.weaponType is WeaponType.Bow => equipEvent.unit.unitData.leftHandPosition,
                EquipmentSlotType.MainHand => equipEvent.unit.unitData.rightHandPosition,
                EquipmentSlotType.OffHand => equipEvent.unit.unitData.leftHandPosition,
                _ => throw new Exception("Equipping weapon in slot other than 'MainHand' or 'OffHand'!")
            };
            
            // Instance of weapon's ONLY model
            equippedModel = Object.Instantiate(parent.weaponData.model, equipPoint, false);
            equippedModel.name = "_model";
            equippedModel.transform.localRotation = parent.weaponData.handRotationOffset;
            equippedModel.transform.localPosition = parent.weaponData.handPositionOffset;
            
            // Instance of point for other hand IK
            equippedModelHandIK = new GameObject();
            equippedModelHandIK.name = "_ik_target";
            equippedModelHandIK.transform.parent = equipPoint.transform;
            equippedModelHandIK.transform.localRotation = parent.weaponData.handRotationOffset;
            equippedModelHandIK.transform.localPosition = parent.weaponData.secondHandPositionOffset;
        }

        private void HideEquipModel(UnEquipEvent unEquipEvent)
        {
            Object.Destroy(equippedModel);
            equippedModel = null;
            Object.Destroy(equippedModelHandIK);
            equippedModelHandIK = null;
        }
    }
}
