using System.Collections;
using UnityEngine;

public class NormaLogic : MonoBehaviour
{
    public float maxUploadTime = 60.0f;

    [SerializeField] private GameObject LeftGun;
    [SerializeField] private GameObject RightGun;
    [SerializeField] private GameObject Target;

    private float completeUpload = 100.0f;
    private float uploadProgress = 0.0f;
    private float speed = 0.0f;

    private bool isUploading;
    public bool uploadCompleted = false;

    Coroutine cor1 = null;
    Coroutine cor2 = null;
    Coroutine cor3 = null;

    public float GetUploadStatus()
    {
        return uploadProgress;
    }

    public void Upload()
    {

        isUploading = !isUploading;

        if (!uploadCompleted)
        {
            if (isUploading)
            {
                if (cor1 != null)
                {
                    HelpingRex(false);
                }

                cor1 = StartCoroutine(Uploading());

            }
            else
            {
                if (cor1 != null)
                {
                    StopCoroutine(cor1);
                }

                HelpingRex(true);
            }
        }

    }


    // Start is called before the first frame update
    void Start()
    {

        speed = completeUpload / maxUploadTime;
        isUploading = false;
        uploadCompleted = false;

        Upload();
    }

    // Update is called once per frame
    void Update()
    {

    }

    IEnumerator Uploading()
    {
        while (true)
        {
            uploadProgress += Time.deltaTime * speed;

            //Debug.Log("uploadProgress: " + uploadProgress);

            if (uploadProgress > 100.0f)
            {
                uploadProgress = 100.0f;
                uploadCompleted = true;
                yield break;
            }
            else
            {
                yield return null;
            }
        }
    }

    private void HelpingRex(bool dothing)
    {

        if (dothing)
        {
            cor2 = StartCoroutine(LeftGun.GetComponent<GunLogic>().SearchAndFire(Target));
            cor3 = StartCoroutine(RightGun.GetComponent<GunLogic>().SearchAndFire(Target));
        }
        else
        {
            if (cor2 != null)
                StopCoroutine(cor2);
            if (cor3 != null)
                StopCoroutine(cor3);
            cor2 = null;
            cor3 = null;
        }




    }



}
