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

class WeaponGun : Weapon
{
    public Transform BulletSpawnTransform;
    public GameObject BulletPrefab;
    public float Accuracy;

    public override void Use(Vector2 aimPos)
    {
        base.Use(aimPos);

        float inaccuracy = 1.0f - Accuracy; 
        aimPos += new Vector2(Random.Range(-inaccuracy, inaccuracy), Random.Range(-inaccuracy, inaccuracy));

        Vector3 aimDirection = new Vector3(aimPos.x, aimPos.y, 0) - BulletSpawnTransform.position;
        Quaternion aimRotation = Quaternion.AngleAxis(-90.0f, Vector3.forward) * Quaternion.LookRotation(Vector3.back, aimDirection);

        GameObject bullet = GameObject.Instantiate(BulletPrefab, BulletSpawnTransform.position, aimRotation);
        Projectile p = bullet.GetComponent<Projectile>();
        p.Damage = this.Damage;
        p.Shooter = Owner;
    }

    public override void UpdatePosition(Transform hand)
    {
        // base.UpdatePosition(hand);
        Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 aimPos = new Vector2(mouseWorldPos.x, mouseWorldPos.y); 
        this.transform.rotation = Quaternion.AngleAxis(90.0f, Vector3.forward) * Quaternion.LookRotation(Vector3.forward, ((Vector3)aimPos - Player.Instance.transform.position));
        float scale = Player.Instance.Controller.collisions.faceDir;
        Vector3 handPos = hand.position + (scale > 0 ? hand.right : hand.right) * 0.05f;
        Quaternion newDr = Quaternion.AngleAxis(180.0f, Vector3.right) * dR;

        if(Player.Instance != null && Player.Instance.Controller != null && this.SpriteRenderer != null) 
        {
            this.SpriteRenderer.flipY = Player.Instance.Controller.collisions.faceDir < 0;
        }
        
        dP = this.HandTransform.position - this.transform.position;
        this.transform.position = handPos - dP;

        Debug.DrawRay(Player.Instance.transform.position, aimPos - (Vector2)Player.Instance.transform.position); 
        Player.Instance.Animator.SetFloat("GunAngle", (Vector2.Angle(Vector2.up, aimPos - (Vector2)Player.Instance.transform.position)) / 180);
    }

}
