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

public class Player : MonoBehaviour
{
    [Header("Stats")]
    public int curHp;
    public int maxHp;
    public float moveSpeed;
    public int damage;

    private Vector2 facingDirection;

    [Header("Combat")]
    public KeyCode attackKey;
    public float attackRange;
    public float attackRate;
    private float lastAttackTime;

    [Header("Experience")]
    public int curLevel;
    public int curXp;
    public int upToNextLevel;
    public float levelXpModifier;


    [Header("Sprites")]
    public Sprite downSprite;
    public Sprite upSprite;
    public Sprite leftSprite;
    public Sprite rightSprite;

    private Rigidbody2D rig;
    private SpriteRenderer sr;
    private ParticleSystem hitEffect;

    void Awake()
    {
        rig = GetComponent<Rigidbody2D>();
        sr = GetComponent<SpriteRenderer>();
        hitEffect = gameObject.GetComponentInChildren<ParticleSystem>();

    }

    void Update() 
    {
        Move();

        if (Input.GetKeyDown(attackKey))
        {
            if (Time.time - lastAttackTime >= attackRate)
                Attack();
        }

    }

    void Attack()
    {
        lastAttackTime = Time.time;

        RaycastHit2D hit = Physics2D.Raycast(transform.position, facingDirection, attackRange, 1 << 8);

        if (hit.collider != null)
        {
            hit.collider.GetComponent<Enemy>().TakeDamage(damage);
            hitEffect.transform.position = hit.collider.transform.position;
            hitEffect.Play();

        }
    }

    void Move()
    {
        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");

        Vector2 vel = new Vector2(x, y);

        if (vel.magnitude != 0)
        facingDirection = vel;

        UpdateSpriteDirection();

        rig.velocity = vel * moveSpeed;
    }

    void UpdateSpriteDirection()
    {
        if (facingDirection == Vector2.up)
            sr.sprite = upSprite;

        else if (facingDirection == Vector2.down)
            sr.sprite = downSprite;

        else if (facingDirection == Vector2.left)
            sr.sprite = leftSprite;

        else if (facingDirection == Vector2.right)
            sr.sprite = rightSprite;
    }

    public void TakeDamage(int damageTaken)
    {
        curHp -= damageTaken;

        if (curHp <= 0)

            Defeat();
    }

    void Defeat()
    {
        UnityEngine.SceneManagement.SceneManager.LoadScene(0);
    }

    public void AddXp (int xp)
    {
        curXp += xp;

        if(curXp >= upToNextLevel)
            LevelUp();
    }

    void LevelUp()
    {
        curXp -= upToNextLevel;
        curLevel++;

        upToNextLevel = Mathf.RoundToInt((float)upToNextLevel * levelXpModifier);

    }


}