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

public class Player : MonoBehaviour
{

    public float movementSpeed;
    public Transform handLocation;
    public BoxCollider2D itemDetecter;
    public bool interacting = false;


    [Header("Sound effects")]
    public AudioClip[] footsteps;
    public float footstepInterval;
    public AudioClip pickItem;

    private float timeSinceLastFootstep;

    private AudioSource audioSource;
    private bool holdingItem = false;
    private Item focusedItem;
    private bool nearItem;

    // Use this for initialization
    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        timeSinceLastFootstep = -footstepInterval;
    }

    // Update is called once per frame
    void Update()
    {
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");
        Vector2 movement = new Vector2(moveX, moveY);
        transform.position = Vector2.MoveTowards(transform.position, (Vector2)transform.position + movement, Time.deltaTime * movementSpeed);

        if (movement != Vector2.zero && Time.time - timeSinceLastFootstep >= footstepInterval)
        {
            SoundManager.instance.PlaySound(footsteps[Random.Range(0, footsteps.Length)], true);
            timeSinceLastFootstep = Time.time;
        }


        //Hold or drop an item
        if (!interacting && !holdingItem && nearItem && Input.GetKeyDown(KeyCode.Z))
        {
            focusedItem.Hold(handLocation);
            focusedItem.GetComponentInChildren<SpriteRenderer>().sortingLayerName = "Character";
            holdingItem = true;
        }
        else if (!interacting && holdingItem && Input.GetKeyDown(KeyCode.Z))
        {
            focusedItem.LetGo();
            focusedItem.GetComponentInChildren<SpriteRenderer>().sortingLayerName = "Default";
            holdingItem = false;
        }


        //Interact with a nearby item
        if (!interacting && !holdingItem && nearItem && Input.GetKeyDown(KeyCode.X))
        {
            focusedItem.Interact();
        }
    }

    public void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Item") && !holdingItem)
        {
            nearItem = true;
            focusedItem = collision.GetComponentInParent<Item>();
        }
        if (collision.CompareTag("SoundEmitter"))
        {
            print("Player near emitter");
            collision.GetComponent<SoundEmitter>().targetVolume = 0.5f;
        }
    }

    public void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.CompareTag("Item"))
        {
            nearItem = false;
            focusedItem = null;
        }
        if (collision.CompareTag("SoundEmitter"))
        {
            print("Player left emitter");
            collision.GetComponent<SoundEmitter>().targetVolume = 0f;
        }
    }
}
