using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class ItemCrate : InteractableObject
{
    public int ItemIndex;
    public Vector2 PreviewDistance;
    public float RotationSpeed = 1.0f;
    public float SizeAnimSpeed = 1.0f; 
    public float PreviewSize = 1.0f; 

    private GameObject preview;
    private float previewAngle = 0;
    private Vector3 initialScale;

    public override void OnInteract(Entity caller)
    {
        if(caller is Player)
        {
            Player p = (Player)caller;
            if(p.EquipInFreeSlot(ItemIndex))
            {
                SetItem(0); 
            }
            else
            {
                UserInterface.Instance.DisplayMessage("CANNOT EQUIP ITEM.", 500.0f, 3.0f); 
            }
        }
    }

    public void SetItem(int id)
    {
        if(preview != null)
        {
            Destroy(preview); 
        }

        if (id != 0)
        {
            Item i = ItemManager.Instance.SpawnWeapon(this.ItemIndex);
            preview = i.gameObject;
            initialScale = preview.transform.localScale;
            Destroy(i); // Destroys the Item Script, not the preview GameObject instance 
        }
    }

    public override void Start()
    {
        base.Start(); 

        if (this.ItemIndex == 0)
        {
            this.ItemIndex = Random.Range(0, ItemManager.Instance.NumItems - 1) + 1; // 0 is hands ... we don't want to give extra hands 
        }
        SetItem(this.ItemIndex); 
    }

    public void Update()
    {
        if(preview != null)
        {
            preview.transform.position = (Vector2)this.transform.position + PreviewDistance;
            preview.transform.rotation = Quaternion.AngleAxis(previewAngle, Vector3.up);
            previewAngle += RotationSpeed * Time.deltaTime;
            preview.transform.localScale = (initialScale * PreviewSize) * (1.0f + (Mathf.Sin(previewAngle / SizeAnimSpeed) * 0.1f));
        }
    }


}
