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

public class SwordAttack : MonoBehaviour, IAction {
    [SerializeField]
    private float m_attackRadius = 0.5f;
    [SerializeField]
	private float m_attackRange = 0.5f;
	[SerializeField] private AudioClip[] m_Sounds;

    private NinjaMovement m_ninjaMovement;
    private Spawner m_spawner;
	private Animator m_animator;

	public void SetSounds(AudioClip[] sounds) {
		m_Sounds = sounds;
	}

    private void Awake()
    {
        m_animator = GetComponent<Animator>();
    }

    void OnDrawGizmosSelected()
    {
        m_ninjaMovement = GetComponent<NinjaMovement>();
        if (!m_ninjaMovement)
            return;

        Gizmos.color = Color.yellow;
        Gizmos.DrawSphere(transform.position, m_attackRadius);
        Vector3 direction = m_ninjaMovement.IsFacingRight() ? Vector3.right : Vector3.left;
        Gizmos.DrawLine(transform.position, transform.position + direction * m_attackRange);
        Gizmos.DrawSphere(transform.position + direction * m_attackRange, m_attackRadius);
    }

    public void doAction() {
        
        Debug.Assert(m_ninjaMovement);
        Vector3 direction = m_ninjaMovement.IsFacingRight() ? Vector3.right : Vector3.left;
        var hits = Physics2D.CircleCastAll(transform.position, m_attackRadius, direction, m_attackRange);
        EventUtil.SendToAll<ISwordAttackEvent>(e => e.OnSwordAttack(gameObject));
        if (hits.Length > 0)
        {
            foreach (var hit in hits)
            {
                if (hit.transform.tag == "Player" && hit.transform.gameObject != gameObject)
                {
					hit.transform.GetComponent<Killable>().Kill(gameObject);
                    m_spawner.SpawnSound(hit.point, SoundType.Big);
                    
                }
            }
        }
        m_animator.SetTrigger("SwordAttack");
        //m_spawner.SpawnSound(transform.position, SoundType.Medium);
        //m_spawner.SpawnAttack(transform.position + direction * m_attackRange);


		var audio = GetComponent<AudioSource> ();
		if (audio != null && m_Sounds.Length>0) {
			audio.PlayOneShot(Util.RandomElement (m_Sounds));
		}
    }

    public int priority() {
        return 0;
    }

    // Use this for initialization
    void Start () {
        m_ninjaMovement = GetComponent<NinjaMovement>();
        m_spawner = Util.Find<Spawner>("Spawner");
    }
	
	// Update is called once per frame
	void Update () {
		
	}
}
