using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets._2D;

public class SoldierShoot : MonoBehaviour {

    public bool canFire = true;
    public GameObject bullet;
    public GameObject TempBullet;
    public float BulletSpeed;
    public Transform muzzle;
    Animator anim;
    public GameObject deathAnimation;
    public AudioSource gunSound;
    bool IsFacingLeft;
    bool IsFacingRight;

    private void Start()
    {
        anim = GetComponent<Animator>();
    }

    void Update()
    {

        if (this.transform.localScale.x == -1) {
            IsFacingLeft = true;
            IsFacingRight = false;
        }

        if (this.transform.localScale.x == 1) {
            IsFacingLeft = false;
            IsFacingRight = true;
        }
        if (Input.GetKeyDown(KeyCode.R))
        {
            Die();
        }
        if (Input.GetKeyDown(KeyCode.E) && canFire && this.transform.tag == "Possessed")
        {
            gunSound.Play();
            canFire = false;
            anim.SetBool("Shoot", true);
        }
    }

    public void Shoot()
    {
        //TempBullet = GameObject.Instantiate(bullet, muzzle.position, muzzle.rotation);
            
            this.gameObject.GetComponent<Platformer2DUserControl>().enabled = false;
            this.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector3(0,0,0);
            anim.SetFloat("Speed",0);
            
            if (IsFacingLeft) {
               
                TempBullet = GameObject.Instantiate(bullet, muzzle.position, muzzle.rotation);
                TempBullet.transform.localScale = new Vector3 (-1,1,1);
                TempBullet.GetComponent<Rigidbody2D>().AddForce(Vector2.left*BulletSpeed);

            }

            if (IsFacingRight) {
                
                TempBullet = GameObject.Instantiate(bullet, muzzle.position, muzzle.rotation);
                TempBullet.GetComponent<Rigidbody2D>().AddForce(Vector2.right*BulletSpeed);

            }
            
    }

    public void BackToIdle()
    {
        anim.SetBool("Shoot", false);
         this.gameObject.GetComponent<Platformer2DUserControl>().enabled = true;
         //this.gameObject.GetComponent<Rigidbody2D>().isKinematic = false;

    }
    public void Die()
    {
        GameObject deathAnim = (GameObject)Instantiate(deathAnimation, transform.position, transform.rotation);
        deathAnim.transform.localScale = gameObject.transform.localScale;
        GameObject flame = deathAnim.transform.Find("Dying Flame").gameObject;

        if (gameObject.tag != "Possessed")
        {

            Destroy(flame);
        }

        Destroy(gameObject);
    }
}
