using UnityEngine;

using System;
using System.Collections;

public class Weapon : MonoBehaviour
{
    private GameObject _Root;

    public GameObject BulletPrefab;
    public Transform WeaponTransform;

    void Start()
    {
        if (WeaponTransform == null)
        {
            WeaponTransform = transform.FindChild("Weapon");
        }

        _Root = GameObject.Find("Bullets");
    }

    public void Shoot()
    {
        if (BulletPrefab != null)
        {
            if (WeaponTransform != null)
            {
                GameObject bullet = (GameObject)Instantiate(BulletPrefab, WeaponTransform.position, WeaponTransform.rotation);

                if (_Root != null)
                {
                    bullet.transform.parent = _Root.transform;
                }
    
                if (gameObject.collider2D != null)
                {
                    if (bullet.collider2D != null)
                    {
                        Physics2D.IgnoreCollision(bullet.collider2D, gameObject.collider2D, true);

                        Bullet bulletScript = (Bullet)bullet.GetComponent(typeof(Bullet));
                        if (bulletScript != null)
                        {
                            bulletScript.Launch(WeaponTransform.right);
                        }
                        else
                        {
                            Destroy(bullet);
                            Debug.LogError("[" + bullet.name + "] Missing Bullet script.");
                        }
                    }
                    else
                    {
                        Destroy(bullet);
                        Debug.LogError("[" + bullet.name + "] Missing Bullet script.");
                    }
                }
                else
                {
                    Destroy(bullet);
                    Debug.LogError("[" + gameObject.name + "] Missing collider2D.");
                }
            }
        }
    }

}
