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

public class WeaponScript : MonoBehaviour
{
    public ParticleSystem muzzle;
    public GameObject spawnpoint;
    public GameObject bullet;

    public DataBullet dataBullet;
    public UI_Manager uI_Manager;

    private InputManagerScript inputManagerScript;

    private int ammo;
    private bool isReloading = false;
    private float time = 0;

    public float reloadTime;

    private bool delayOver = true;
    public float schussInterval;
    private float delay = 0;

    public Animator animator;
    public void checkReload(){
        if(ammo == 0 || Input.GetKeyDown(inputManagerScript.getReload())){
            isReloading = true;
        }
        if(isReloading){
            time += Time.deltaTime;
            if(time > reloadTime){
                ammo = dataBullet.ammo;
                uI_Manager.ammoReset();
                time = 0;
                isReloading = false;
                //animator.SetBool("isReloading",false);
            }
        }
        animator.SetFloat("speed",1 / reloadTime);
        animator.SetBool("isReloading",isReloading);
    }
    public void shoot(){
        if(!isReloading && delayOver){
            if(Input.GetKeyDown(inputManagerScript.getShoot())){
                    muzzle.gameObject.SetActive(true);
                    //muzzle.Play();
                    Instantiate(bullet,spawnpoint.transform.position,spawnpoint.transform.rotation);
                    ammo--;
                    uI_Manager.ammoDown();
                    delay = 0;
                    delayOver = false;
            }         
        }
    }
    public void checkDelay(){
        if(!delayOver){
            delay += Time.deltaTime;
            if(delay > schussInterval){
                delayOver = true;
            }
        }
    }
    void Start()
    {
        ammo = dataBullet.ammo;
        muzzle = GetComponentInChildren<ParticleSystem>();
        spawnpoint = GameObject.Find("Player/PlayerView/BulletSpawnpoint");
        uI_Manager = GameObject.FindGameObjectWithTag("Manager").GetComponent<UI_Manager>();
        inputManagerScript = GameObject.Find("InputManager").GetComponent<InputManagerScript>();

    }

    // Update is called once per frame
    void Update()
    {
        checkDelay();
        shoot();
        checkReload();
    }
}
